1

I have the following code:

$recommended_args = 
    array(
            'post_type' => 'post',
            'posts_per_page' => 3,
            'post__in' => get_option('sticky_posts'),
            'orderby' => 'date'
        );

$recommended_query = new WP_Query($recommended_args);
if ($recommended_query->have_posts()) {
    while($recommended_query->have_posts()) {
        $recommended_query->the_post();
        get_template_part("templates/article-random");
    }
}

Basically, it should return the 3 most recent posts marked as sticky. However, it dumps all (more than 3) sticky posts in the DB onto the screen.

What is wrong with the arguments? Is there a way to fix this without having to replace the while loop with a for loop that iterates only over the first 3 in the WP_Query object?

2

This is default behavior when the post__in parameter is used. If you read the docs, you will see that you should set 'ignore_sticky_posts' => 1 to eliminate sticky posts being queried

EDIT

Your query arguments should look like this

$recommended_args = array(
    'post_type' => 'post',
    'posts_per_page' => 3,
    'post__in' => get_option('sticky_posts'),
    'orderby' => 'date',
    'ignore_sticky_posts' => 1
);

EDIT 2

By default, WP_Query (no matter if this is the main query or a custom query) searches and returns all sticky posts at the top of the first page. All other query parameters are ignored, specially posts_per_page. If you have 100 stickies, and posts_per_page is set to 3, all 100 sticky posts will be returned regardless with 3 posts that is not in the sticky posts array

These sticky posts is then removed from its original place in the query to avoid duplicates. When you pass get_option( 'sticky_posts' ) to post__in, these sticky posts are simply removed from the query as WP_Query has already returned them as sticky posts, this is to avoid them being shown as duplicates.

To make your query work, you have to "switch" off the sticky posts feature so that WP_Query can exclude them and just focus on the query at hand. For this you will need to set the ignore_sticky_posts paramter to 1 which means that sticky posts will be ignored

I hope this makes sense now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.