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

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.

Leave a Comment