0

I'm trying to list a few post sorting by a custom field value ("space-comments"). It's working very well, however, when the custom field is empty the loop don't get this post.

Any idea to fix it? Thanks :)

            $args = array( 
                'post_type' => 'spaces',
                'post_per_page' => '500',
                'meta_key' => 'space-comments',                 
                'orderby' => 'meta_value_num',                  
                'order' => 'DESC',
                'author__in' => $tradicionalIds,
                    'meta_query' => array(
                        'relation' => 'AND',                            

                        array(
                            'key' => 'space-city',
                            'value' => $search,
                            'compare' => 'LIKE'
                       ),
                        array(
                            'key' => 'space-comments',
                            'compare' => 'EXISTS',                              
                        ),          

                    )
                );



            $query = new WP_query($args);

2 Answers 2

0

I found an other post on stackexchange that seems to answer your question:

Order by optional meta key?

0

To sort posts by custom field values, including posts with empty custom field values, you need to adjust your meta_query parameter. Instead of using 'compare' => 'EXISTS', you should use 'compare' => 'EXISTS' for posts that have a value for the custom field and another meta_query array with 'compare' => 'NOT EXISTS' for posts with empty values

$args = array( 
    'post_type' => 'spaces',
    'posts_per_page' => 500, // It should be 'posts_per_page' not 'post_per_page'
    'meta_key' => 'space-comments',                 
    'orderby' => 'meta_value_num',                  
    'order' => 'DESC',
    'author__in' => $tradicionalIds,
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key' => 'space-city',
            'value' => $search,
            'compare' => 'LIKE'
        ),
        array(
            'relation' => 'OR',
            array(
                'key' => 'space-comments',
                'compare' => 'EXISTS'
            ),
            array(
                'key' => 'space-comments',
                'compare' => 'NOT EXISTS',
                'value' => ''
            )
        )
    )
);

$query = new WP_Query($args);

please modified your query will retrieve posts with non-empty custom field values for space-comments as well as posts with empty values for space-comments

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.