How to order posts by meta value?

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' );

Leave a Comment