How to sort by meta value num, but ignore zero value?

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.

Topic meta-value post-meta sort Wordpress

Category Web


You can use a meta_query in your WP_Query

$args = array(
    'post_type'  => 'company',
    'meta_query' => array(
        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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.