0

All posts are using a custom field "deadline" (format: yyyy-mm-dd). How do I make my category page order posts by meta_key "deadline" and DESC? I use this:

if ( get_query_var( 'paged' ) ) { 
    $paged = get_query_var('paged'); 
} elseif ( get_query_var( 'page' ) ) { 
    $paged = get_query_var( 'page' ); 
} else { 
    $paged = 1; 
}
query_posts( array( 
    'paged'    => $paged , 
    'cat'      => $category_id , 
    'meta_key' => 'deadline' , 
    'orderby'  => 'meta_value' , 
    'order'    => 'DESC' 
));
get_template_part( 'loop' );

but it doesn't work to order posts by meta_value.

2
  • Never use query_posts, it will cause problems (like breaking pagination). Use WP_Query or get_posts instead.
    – Gabriel
    Jul 16, 2015 at 2:30
  • What does it do instead?
    – s_ha_dum
    Jul 16, 2015 at 4:13

1 Answer 1

0

As mentioned above, never use query_posts, as it breaks a lot of stuff. Use a filter like pre_get_posts instead. The filter pre_get_posts allows you to edit the query before it gets executedby WP. The following code will order by the meta value you want. I made it so it only works on the main query of a page and with the post type post, but you can edit it filter it further:

function wpse194643_special_sort( $query ) {
    //is this the main query and is this post type of post
    if ( $query->is_main_query() && $query->is_post_type( 'post' ) ) {
        //Do a meta query
        $query->set( 'meta_query', array(
            array( 'key' => 'deadline' )
        ) );
        //sort by a meta value
        $query->set( 'orderby', 'meta_value' );
        $query->set( 'order', 'DESC' );
    }
}
add_action( 'pre_get_posts', 'wpse194643_special_sort' );
2
  • I got error message: Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in xxx/custom-functions.php on line 58 Jul 16, 2015 at 6:07
  • Fixed. Try it now Jul 16, 2015 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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