posts_per_page不适用于新的wp查询

Lau*_*ize 1 wordpress

我需要将post_per_page设置为仅显示1条帖子,这是我使用的代码:

<?php
$yell = new WP_Query(array('posts_per_page' => 1,'post_type' => 'items', 'portfolio-category' => 'accessories'));
while ($yell->have_posts()) : $yell->the_post();
?>

<h2><?php the_title(); ?></h2>

<?php endwhile; wp_reset_query(); ?>
Run Code Online (Sandbox Code Playgroud)

但它没有显示1个帖子,而是显示了所有帖子。不知道为什么

Pat*_*Pat 5

您可以使用post_limits过滤器执行此操作

add_filter('post_limits', 'your_query_limit');
function your_query_limit($limit){
    return "LIMIT 1";
}
Run Code Online (Sandbox Code Playgroud)

更新:如果只希望针对自定义查询运行此操作,则可以执行以下操作:

  1. 添加它。
  2. 运行自定义查询。
  3. 去掉它。

代码如下:

add_filter('post_limits', 'your_query_limit');
$yell = new WP_Query(
    array(
        'post_type' => 'items', 
        'portfolio-category' => 'accessories'
    )
);
remove_filter('post_limits', 'your_query_limit');
Run Code Online (Sandbox Code Playgroud)