0

I'm struggling with the orderby option of a Wordpress query. I want to order a list of posts, ordered by if a values exists for the key 'other-value'. And then on how many clicks the items has.

  1. So first the posts with an existing value, and then the posts that don't have that value.
  2. Then in the existing and non-existing posts an order of users clicks with the key 'sort-by-clicks'.

Query

'meta_query'    => array(
    'relation' => 'OR',
    array(
        'relation' => 'AND',
        array(
            'key' => 'sort-by-clicks'
        ),
        array(
            'key' => 'other-value',
            'compare' => 'EXISTS',
        )
    ),
    array(
        'relation' => 'AND',
        array(
            'key' => 'sort-by-clicks'
        ),
        array(
            'key' => 'other-value',
            'compare' => 'NOT EXISTS',
        )
    )
),

I've tried to ad extra parameters to order it by, but I can't figure out whats the right approach.

Non succesfull orderby's `

'othervalue' => array(
            'key' => 'other-value',
            'compare' => 'EXISTS',
        )

And then ad an orderby

'orderby'  => array(
    'othervalue' => 'DESC'
)

I guess this is the right approach, but I don't see the end of the puzzle

1 Answer 1

0

I have got the solution. Please try to use below code:

$args = array(
    'post_type'  => 'post_type_name',
    'meta_query' => array(
        'relation' => 'AND',
        'sortbyclicks' => array(
            'key'     => 'sort-by-clicks',
            'compare' => 'EXISTS',
        ),
        'othervalue' => array(
            'key'     => 'other-value',
            'compare' => 'EXISTS',
        ), 
    ),
    'orderby' => array(
        'othervalue' => 'DESC',        
    ),
);

$loop = new WP_Query( $args );

Thanks!!

3
  • Thanks for the quick response. But your solution only show the posts where the other-value exists. I also want to show the posts where the other-value doesn't exists Dec 18, 2018 at 12:37
  • So, you can change the 'relation' value in wp query like 'relation' => 'OR', ...Try it Dec 18, 2018 at 12:55
  • I think this isn't the solution I'm looking for. This is the output I need: - value exist 20 clicks - value exist 3 clicks - value does not exist 22 clicks - value does not exist 5 clicks Dec 18, 2018 at 13:52

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.