wp query - Order by empty custom field

admin2025-01-07  4

I order my posts by custom field faq-order. That's work for me:

$faqArgs = array(
    'post_type' => 'faq',
    'meta_key' => 'faq-order',
    'order' => 'ASC',
    'orderby' => 'meta_value_num',
);

$faq = new WP_Query($faqArgs);

But post disappear from result response if those field faq-order is empty. How can I fix it? How can I use default value (for example 0), if that field is empty?

I order my posts by custom field faq-order. That's work for me:

$faqArgs = array(
    'post_type' => 'faq',
    'meta_key' => 'faq-order',
    'order' => 'ASC',
    'orderby' => 'meta_value_num',
);

$faq = new WP_Query($faqArgs);

But post disappear from result response if those field faq-order is empty. How can I fix it? How can I use default value (for example 0), if that field is empty?

Share Improve this question asked Jun 4, 2018 at 23:59 Display NameDisplay Name 111 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

There are two solutions for that:

1. Make sure that all posts have that field set.

You can do this easily - just use save_post hook and set it to default value. (You should also add default values for already existing posts that don't have that field set.)

2. Use a little bit modified query

$faqArgs = array(
    'post_type' => 'faq',
    'meta_key' => 'faq-order',
    'order' => 'ASC',
    'orderby' => 'meta_value_num',
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'faq-order', 
            'value' => 'bug #23268', 
            'compare' => 'NOT EXISTS'
        )
    )
);
$faq = new WP_Query($faqArgs);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736260656a681.html

最新回复(0)