简体   繁体   English

仅过滤Wordpress中的博客文章

[英]Filter Only the Blog Posts in Wordpress

I want to display the latest 2 blog posts in my footer. 我想在页脚中显示最新的2篇博客文章。 I used while (have_posts()) : the_post(); 我用了while (have_posts()) : the_post(); to display all the blog posts in my blog page ( Almost it's the index page in my case ). 以显示我的博客页面中的所有博客文章(在我的情况下,这几乎是索引页面)。

When I tried to filter the latest to blog posts using the same approach I was unable to achieve that. 当我尝试使用相同的方法过滤最新的博客文章时,我无法实现。

This is the code so far I have tried. 到目前为止,这是我尝试过的代码。 I used a for loop to limit the number of posts. 我使用了for loop来限制帖子的数量。

<ul class="widget-post-list">
     <?php if (have_posts()) : while (have_posts()) : the_post(); for ($i = 0; $i <2; $i ++){ ?>

     <li>
       <h5 class="post-title"><a href="<?php echo get_permalink() ?>"><?php echo wp_trim_words(get_the_title(), 14); ?></a></h5>
     </li>

     <?php } endwhile; else: ?>
       <h5>No Posts found.</h5>
     <?php endif; ?>
</ul>

Through this code I am only returned the Home page link twice. 通过此代码,我只返回了两次Home链接。

What is problem here? 这是什么问题? or is there any other way that I can try? 还是我可以尝试其他方法?

Use this in order to display 2 posts, you can change the ul li according to your convenience, 使用它来显示2个帖子,您可以根据需要更改ul li,

you can use posts_per_page option to filter 2 posts 您可以使用posts_per_page选项过滤2个帖子

<ul class="widget-post-list">
// Define our WP Query Parameters
<?php $the_query = new WP_Query( 'posts_per_page=2' ); ?>

// Start our WP Query
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>

// Display the Post Title with Hyperlink
<li><h5 class="post-title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h5></li>

// Repeat the process and reset once it hits the limit
<?php 
endwhile;
wp_reset_postdata();
?>
</ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM