How to filter WP_Query with 'orderby' (ASC & DESC) with meta_query?

Viewed 16

I'm trying to filter posts by 'DESC' with custom meta: 'like_count_on_post', then collecting all empty 'like_count_on_post' with 'dislike_count_on_post', and then finishing with 'ASC' of 'dislike_count_on_post', but I only get likes descending, or if I remove:

'custom_field_value' => 'DESC'

I can get ascending of dislikes, but not both.

The query arguments code:

        $args = array(
        'post_status' => 'publish',
        'post_type' => 'sveikinimai',
        'meta_query' => array(
            "relation" => "and",
            'likes' => array(
                "relation" => "or",
                'custom_field_value' => array(
                    'key' => '_like_count_on_post_',
                ), 
                'custom_field' => array(
                    'key' => '_like_count_on_post_',
                    'compare' => 'NOT EXISTS',
                ),
            ),
            'dislikes' => array(
                "relation" => "or",
                'custom_field_value_2' => array(
                    'key' => '_dislike_count_on_post_',
                ), 
                'custom_field_2' => array(
                    'key' => '_dislike_count_on_post_',
                    'compare' => 'NOT EXISTS',
                ),
            ),
        ),
        'orderby' => array(
            'custom_field_value' => 'DESC',
            'custom_field_value_2' => 'ASC'
        ),
        'posts_per_page' => 20,
        'paged' => $paged,
    );

Update, here is code if you want to filter without non existing meta fields:

        $args = array(
            'post_status' => 'publish',
            'post_type' => 'sveikinimai',
            'meta_query' => array(
                "relation" => "and",
                'custom_field_value' => array(
                    'key' => '_like_count_on_post_',
                ), 
                'custom_field_value_2' => array(
                    'key' => '_dislike_count_on_post_',
                ), 
            ),
            'orderby' => array(
                'custom_field_value' => 'DESC',
                'custom_field_value_2' => 'ASC'
            ),
            'posts_per_page' => 20,
            'paged' => $paged,
        );
1 Answers

To solve problem, I added to all posts 'like_count_on_post' and 'dislike_count_on_post' meta fields. Filter working as it should, I suppose doesn't resolve when fields empty, but here is code to make those fields not empty:

add_action('save_post', 'add_post_custom_meta'); 
function add_post_custom_meta() {
  global $post;
  $post_id  = $post->ID;

  update_post_meta($post_id, '_like_count_on_post_', 0);
  update_post_meta($post_id, '_dislike_count_on_post_', 0);
}
Related