Ensuring sticky posts are retrieved first (without using two queries)?

I need to maintain pagination for use with infinite scroll.

Is there no way to tell query_posts to retrieve sticky posts first?

Read More

It seems to be default behaviour on a standard wordpress blog on the home page, but becomes a bit awkward on a custom template for a page from what I can tell.

Thank you.

Edited to show current query:

query_posts( array( 
    'post_type' => array('post', 'careers-post'),
    'paged' => $paged,
    'posts_per_page' => 6,
    'category__in' => $page_categories,
    'ignore_sticky_posts' => 0
) );

Edit 2:
Seems like “category__in” has a conflict with sticky posts dating back a long time: http://wordpress.org/support/topic/category_in-ampamp-sticky

Just to confirm, removing “category__in” does indeed let sticky posts bubble to the top as expected, but obviously doesn’t solve the problem.

Related posts

Leave a Reply

1 comment

  1. Digging through the source code I couldn’t really find any weird logic that would cause ‘category__in’ to break the ordering of the results. If you do, you might as well file a bug in the WordPress Trac.

    It’s also hard to reproduce this sort of issue, because it might depend on another issue which is specific to your database or how the data was previously manipulated by custom code.

    Regardless, with a bit of effort you can always work around this kind of issue. Here’s something that will filter your query results and send sticky posts to the top:

    add_filter('the_posts', 'bump_sticky_posts_to_top');
    function bump_sticky_posts_to_top($posts) {
        $stickies = array();
        foreach($posts as $i => $post) {
            if(is_sticky($post->ID)) {
                $stickies[] = $post;
                unset($posts[$i]);
            }
        }
        return array_merge($stickies, $posts);
    }
    

    Since your limiting the query to 6 posts, I don’t foresee any significant impact on processing time. You can also put additional checks inside the function so this filter will only run when you’re using that specific query (although if you don’t the worst I can imagine happening is doubling-up on something that WP has already done).

    Hope it helps! Let us know how it goes.