Finding any way to push old posts into the WP_Query using custom fields. For example I have 10 posts in this year, and want to republish 2 posts from the past to custom rss feed.

So the posts must be ordered by post date and value in the post meta for old posts:

new post - (post date: 2018-11-11)
new post - (post date: 2018-11-10)
old post - (post date: 2017-05-01, post-meta date: 2018-11-09)
new post - (post date: 2018-11-08)

I try to order by 2 values in WP_Query but it is not working

   add_filter('pre_get_posts', function($query) {
        if($query->is_main_query() && $query->is_feed()) {
            $query->set('posts_per_rss', 3);
            $query->set('post_type', 'post');
            $query->set('post_status', 'publish');

            $query->set('meta_query', [
                'relation' => 'OR',
                'push_clause' => [
                    'key' => 'is-push',
                    'compare' => 'EXISTS'
                'exclude_clause' => [
                    'key' => 'is-exclude',
                    'compare' => 'NOT EXISTS'

            $query->set('orderby', ['push_clause' => 'DESC']);

Is there any way to implement this using WP_Query?

Update: I've written pure sql query, working sorting as I want

SELECT SQL_CALC_FOUND_ROWS wp_posts.post_title, wp_posts.post_date, m.*, IFNULL(m.meta_value, wp_posts.post_date) as d
FROM wp_posts  
LEFT JOIN wp_postmeta m ON (wp_posts.ID = m.post_id AND m.meta_key = 'is-push')
WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' 
     d DESC

1 Answer 1


Finally I've decided to use custom sql query with get_results method.

$query = "SELECT SQL_CALC_FOUND_ROWS p.*, IFNULL(m2.meta_value, p.post_date_gmt) as zen_date
            FROM {$wpdb->posts} p
            LEFT JOIN {$wpdb->postmeta} m1 ON (p.ID = m1.post_id AND m1.meta_key = 'is-exclude')
            LEFT JOIN {$wpdb->postmeta} m2 ON (p.ID = m2.post_id AND m2.meta_key = 'is-push')
            WHERE p.post_type = 'post' AND p.post_status = 'publish' AND m1.post_id IS NULL
            GROUP BY p.ID ORDER BY zen_date DESC LIMIT 0, 50";

$posts = $wpdb->get_results($query, OBJECT);

foreach($posts as $post) {

    // do something

If somebody suggests something better, I'll be glad to accept that answer.

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.