Skip to content
Advertisement

Orderby function with unexpected result

I have setup a query to list my posts ordered by a certain custom field (which is the publish date of the individual books reviewed in my blog).

$the_query = new WP_Query(array(
    'post_type'         => 'book',
    'posts_per_page'    => 10,
    'meta_key'          => 'book_release_date',
    'meta_type'         => 'NUMERIC',
    'orderby'           => 'meta_value',
    'order'             => 'DESC'
));

I have then called it this way:

<?php if( $the_query->have_posts() ): ?>
<?php if (is_category()) { ?>
<div class="page-title" align="center">
<h2 class="page-title-border">
<?php _e(' Books:'); ?> 
<?php echo single_cat_title(); ?> (<?php echo $wp_query->found_posts; ?>) 
</h2>
</div>
<?php } ?><?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>

There’s a problem tho: homepage shows posts basing on last released book order, BUT each category, research etc now always shows as result, the last released books in general, without respecting the category requested nor the keyword used for the research.

Why is this happening?

The weird part is if I add <?php wp_reset_query(); ?> just after the latest row above, it will correctly show a correct result, but first result is displayed 10x times, always the same.

Advertisement

Answer

Replace your custom WP_Query with the following:

set_query_var( 'orderby', 'meta_value' );
set_query_var( 'orderby', 'DESC' );
set_query_var( 'meta_key', 'book_release_date' );
set_query_var( 'meta_type', 'NUMERIC' );

It sounds like you had a working list of Books that filtered by Category, etc., and now you are trying to tap into that list to add the orderby. If so then I see one problem: Your posted code would lose the filtering because you’ve created an entirely new post loop. The fact that wp_reset_query restores the filtered posts-loop leads me to believe that we can simply amend this existing query via set_query_var versus create a new WP_Query.

BONUS: If you are using pre_get_posts in your functions.php then do the following:

function wpse139657_orderby($query){ 
    // Uncomment this if() statement once you confirm that the orderby works
    //if (is_admin() || $query->query_vars['post_type'] != 'book') return $query;

    $query->set( 'orderby', 'meta_value' ); 
    $query->set( 'order', 'DESC' ); 
    $query->set( 'meta_key', 'book_release_date' ); 
    $query->set( 'meta_type', 'NUMERIC' );

    return $query;
} 
add_filter('pre_get_posts','wpse139657_orderby');
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement