【问题标题】:How to get latest three posts from the same category?如何获取同一类别的最新三个帖子?
【发布时间】:2019-06-17 09:54:50
【问题描述】:

我正在使用 WordPress 和 PHP 创建一个新网站。我需要从我当前所在的帖子的同一类别中获取最新的三个帖子。另外,我需要避免我正在观看的帖子进入三个帖子的列表。

我尝试了下面的代码,所以目前我只能显示三个帖子的名称,即使它们不属于同一类别...

<?php
$args = array( 'numberposts' => 3 );
$lastposts = get_posts( $args );
foreach($lastposts as $post) : setup_postdata($post); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>      
</h2>
<?php endforeach; ?>

我除了三个最新的帖子是网站页面的同一类别。

【问题讨论】:

标签: php wordpress


【解决方案1】:

您需要在代码中添加类别参数。

$category_id = 1;
$posts= new WP_Query(array(
    'cat'            => $category_id,
    'posts_per_page' => 3
));

然后使用它访问它

<?php while ( $posts->have_posts() ) : $posts->the_post(); ?>
            <?php the_title(); ?>
<?php endwhile; ?>

【讨论】:

猜你喜欢
  • 2014-07-19
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
相关资源
最近更新 更多