【问题标题】:Filter Only the Blog Posts in Wordpress仅过滤 WordPress 中的博客文章
【发布时间】:2018-09-11 06:12:42
【问题描述】:

我想在页脚中显示最新的 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 页面链接。

这里有什么问题?或者有没有其他方法可以尝试?

【问题讨论】:

  • while 将循环帖子,再次使用 'for' 循环的目的是什么,尝试将 WP_Query 与 $args 一起使用
  • @charankumar while 循环将加载所有可用的帖子。但我只需要最新的 2 个帖子。所以我保留了 for 循环。

标签: php wordpress blogs


【解决方案1】:

使用这个来显示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>

【讨论】:

    猜你喜欢
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多