Order Posts by meta value AND published date

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',
                        array(
                            'key'     => $meta_key,
                            'compare' => 'NOT EXISTS',
                        ),
                        array(
                            'relation' => 'OR',
                            array(
                                'key'   => $meta_key,
                                'value' => 'on',
                            ),
                            array(
                                '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.

1 Answer
1

'orderby' => 'date meta_value_num', 
'meta_key'  => $meta_key,
'order' => 'DESC'

Leave a Comment