posts_per_page not working for new wp query

2019-08-03 05:25发布

问题:

I need to set the post_per_page to display only 1 post here's the code I use:

<?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(); ?>

But it doesn't show 1 post, it shows all. not sure why

回答1:

You can do it with the post_limits filter:

add_filter('post_limits', 'your_query_limit');
function your_query_limit($limit){
    return "LIMIT 1";
}

Update: If you only want this to run for your custom query, you could do the following:

  1. Add it.
  2. Run the custom query.
  3. Remove it.

Code would be like so:

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');


标签: wordpress