WP_Query post at custom position

Pagination should be easy. You really just need to add pagination parameters to your query, and next/previous posts links, more or less like in another thread I posted in recently.

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$my_query = new WP_Query( 
    array(
        'showposts'=>10,
        'paged'    => $paged 
    )
); 
// run the loop then, 
// pagination links ...
var_dump(paginate_links( array(
    'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format' => '?paged=%#%',
    'prev_text' => __('« Previous'),
    'next_text' => __('Next »'),
    'current' => max( 1, get_query_var('paged') ),
    'total' => $my_query->max_num_pages
) ));

But… getting a two to one ratio in every result set isn’t.

I believe that I could pull this off with a custom SQL query (using a UNION) and $wpdb->get_results or $wpdb->get_col. However, the pagination would be a little tricky and you don’t get WordPress post objects that way so chances are you’d need a second query to create those (and you nearly always need them). The minimal SQL would look something like…

(SELECT ID FROM {$wpdb->posts} WHERE post_type="post-type-1" LIMIT a,b) UNION ALL (SELECT ID FROM {$wpdb->posts} WHERE post_type="post-type-2" LIMIT c,d)

The tricky part is getting the values for those LIMITs right.

In principle, with the right filters– posts_where, posts_fields, etc.— you should be able to alter a query to match the custom SQL alluded to above, but again the pagination would be a little tricky and the actual query that WP_Query uses is more complicated so you’d have to match that when you build the UNION.

With either of those solutions it might be necessary to sort the results before echoing them. I’d have to set up the queries, test it, and see.

Ultimately, I can’t convince myself that that either of those solutions are better than the simple and obvious one of just running two queries. I understand that you want to keep the query counts down. So do I, but sometimes two queries is the right move. Unless your server is severely underpowered or your site very badly designed in many other ways, two queries vs one for this page won’t make a difference.

So…

Is it possible in ONE query with filters or any other way ?

Yes, I think it is possible but you would have to use filters to radically alter the query and I don’t think it is worth the time it would take to develop the solution and I don’t think it is worth the saving in execution time that you may or may not get out of it.

Leave a Comment