I have custom-post-type company and taxonomy services for this CPT. I have created meta-field service_[id]_price for companies and fill this field with a number. If this company has not price for this service, I fill 0 in this field.

On the services page, I need a list of companies sorted by current service price ASC. In this case, I first get all companies with "0" value in this field. But I need to get all companies where this field has not zero value in ASC order - first, and all that have value '0' at the end.

  • consider not saving anything under the key if there is no price, rather than zero. you can query for posts both where a meta key does and does not exist, and have the posts where it does exist appear first. – Milo Jan 27 '16 at 19:43

You can use a meta_query in your WP_Query

$args = array(
    'post_type'  => 'company',
    'meta_query' => array(
            'key' => 'service_XXXX_price',
            'value' => '0',
            'compare' => '!=',
$company_query = new WP_Query( $args );

You can find more infos about the meta querys in the codex: https://codex.wordpress.org/Class_Reference/WP_Query

  • In this case I just exclude services with price = 0. But I need to get all companies and sort it: Part-1: with service price > 0 in ASC order, Part-2: with service price = 0 – Artur Jan 27 '16 at 20:00
  • I think I need to JOIN two queries here... – Artur Jan 27 '16 at 20:15
  • You can use an if-statement. If the value is 0, then copy it in an array, else echo the post. At the end you can echo the posts from the 0-array – Sören Wrede Jan 27 '16 at 22:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.