我想在我的页脚中显示最新的2篇博文。我使用while (have_posts()) : the_post();
来显示我博客页面中的所有博客文章(在我的案例中几乎是索引页面)。
当我尝试使用相同的方法过滤最新的博客文章时,我无法实现这一点。
这是我尝试过的代码。我用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>
通过这段代码,我只返回两次
Home
页面链接。
这有什么问题?或者还有其他方法可以尝试吗?
使用此功能以显示2个帖子,您可以根据自己的方便更改ul li,
你可以使用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>