I want to order WP posts by meta key named "sort_date" and if it doesn't exist it should use the post's published date to order posts.

Below is the code i am currently using

            function pre_get_posts_custom($wp_query) { 

              if ( !is_admin() && $wp_query->is_main_query() && !is_page() )
                    $meta_key = 'sort_date';
                    $wp_query->set( 'post_type', array( 'post', 'article' ) );  
                    $wp_query->set( 'meta_type', 'DATE' );  
                    $wp_query->set('meta_query', array(
                        'relation' => 'OR',
                            'key'     => $meta_key,
                            'compare' => 'NOT EXISTS',
                            'relation' => 'OR',
                                'key'   => $meta_key,
                                'value' => 'on',
                                'key'     => $meta_key,
                                'value'   => 'on',
                                'compare' => '!=',
                    $wp_query->set( 'orderby', array( 'meta_value' => 'DESC', 'date' => 'DESC' ) );

            add_filter('pre_get_posts', 'pre_get_posts_custom' );

The above code makes the posts having "sort_date" meta key appear first and then all posts with no meta key value.

For example

Post A: has meta key value 2016-9-28

Post B: No meta key...published date is 2017-6-15

The above code makes the post A appear first, i want post B to appear first as it has most recent date. I want both meta key value and published date to work as one instead of sorting both separately.

  • I'm not sure it's possible to achieve this through wp_query. You are essentially trying to introduce conditional logic into the 'orderby' which isn't possible. You would have to get this result by creating a complex SQL query to run directly on the database instead of going through wp_query. – FluffyKitten Oct 1 '17 at 5:23
  • My suggestion would be to give the sort_date meta_key a default value of the published date when its created - this would then remove the need for a complex wp_query and make it trivial to sort by date. – FluffyKitten Oct 1 '17 at 5:27
'orderby' => 'date meta_value_num', 
'meta_key'  => $meta_key,
'order' => 'DESC'
  • Would you be so kind an explain a bit why this is the solution and works? – kaiser Sep 30 '17 at 23:20
  • It doesn't seem to work. It is still ordering them in groups, one with meta value and other with published date. – Ehsan Oct 1 '17 at 1:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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