RItika
RItika

Reputation: 103

sort by two meta keys

I'm trying to order data with two meta keys but I'm not able to do that.

This code is not working for me:

 $args= array(
  "post_type" => "post_type",
  "post_status" => "publish",
  'meta_query'    => array(

                            array(
                                'key'     => 'keyname1',
                                'orderby' => 'meta_value_num',
                                'order' => DESC,
                            ),
                                 array(
                                'key'     => 'keyname2',
                                'orderby' => 'meta_value_num',
                                'order' => DESC,
                            ),

),


  "posts_per_page" => 10
);

This code works for the single key perfectly, but not for the two keys:

$args=array(
      "post_type" => "post_type",
      "post_status" => "publish",
      "orderby" => array(
      "meta_value_num" => "DESC",
      "rand" => "ASC" ),
      "meta_key" => "keyname",);

How can I do this?

Upvotes: 0

Views: 318

Answers (2)

vikas pandey
vikas pandey

Reputation: 204

After add 'relation'=>'OR' try this i think work well

<?php
$_query = new WP_Query( array(
        'post_type'         => 'post_type',
        'post_status'       => 'publish',
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'key1'
            ),
            array(
                'key'     => 'key2'
            ),
        ),
    ) );
?>

Upvotes: 0

RItika
RItika

Reputation: 103

I have figured out the solution thanks @Jomal John for reminding me this solutions again. Here's the answer might me helpful for someone.

$args=array(
  "post_type" => "post_type",
  "post_status" => "publish",
  "meta_query"    => array(

             'key_1_clause' => array(
            'key' => 'key_1',

        ),
     'key_2_clause' => array(
            'key' => 'key_2',

        ),


),
    'orderby' => array(
     "meta_value_num" => "DESC",
        'key_1_clause' => 'DESC',
        'key_2_clause' => 'DESC',
    ),

 "posts_per_page" => 10
);

Upvotes: 1

Related Questions