0

I want to create a query of a custom post type where the order is by a custom field and I want if the custom fields are equal to compare a second custom field.

$args = array (
    'post_type' => array( 'sn_dr_ia' ),
    'orderby'   => 'meta_value_num',
    'meta_key'  => 'thePrice',
);

These are my arguments and the result is ordering by thePrice field correctly and I want if thePrice field are equal to compare it with thePrice2

4
  • You want to sort the results by the value of the meta field thePrice and in the second comparison by meta field thePrice2, correct?
    – David
    Jul 27, 2016 at 9:40
  • @David Yes, i want the sorting to be by the thePrice meta field and if the two metas are equal the compare it with thePrice2 meta field
    – Stelios k
    Jul 27, 2016 at 10:05
  • I have trouble following this. Do you want posts that have thePrice and thePrice2, equal to value? What the point of two different fields equal to each other?
    – Rarst
    Jul 27, 2016 at 13:28
  • @Rarst I need a query where the order is by thePrice, the price is meta field that takes values from 0-10. Lets say its olympic medals. I want to order all the countries that they have the most gold medals, and if three countries has the same gold medals i want to be ordered by the silver medals. Now u get me?
    – Stelios k
    Jul 27, 2016 at 15:24

1 Answer 1

1

You need to setup multiple meta_queries using an array. Since you didn't have a value you were looking for I'm just making sure that thePrice and thePrice2 are not blank. I set each meta query to a variable and then used them in the main orderby statement with a space between them. I wasn't able to do any testing on the code so if you have issues let me know.

<?php
$args = array(
    'post_type' => 'sn_dr_ia',
    'meta_query' => array(
        'relation' => 'OR',
        'thePriceValue' => array(
            'key'     => 'thePrice',
            'value'   => '',
            'compare' => '!='
        ),
        'thePrice2Value' => array(
            'key' => 'thePrice2',
            'value'   => '',
            'compare' => '!='
        )
    ),
    'orderby' => 'thePriceValue thePrice2Value',
    'order'   => 'ASC'
);

$query = new WP_Query($args);
?>

Here is a link to the codex for the syntax of the meta_query: https://codex.wordpress.org/Class_Reference/WP_Meta_Query

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.