Search code examples
phpwordpressnull

show query meta_key_value including null value


I am trying to do a simple query in WordPress ordered by a meta_value_num of a custom field, the problem is that not all the inputs have a value so it gives me a null value and it does not show very well in the query, it only shows the ones that have value, I have this code:

<ul class="post">
    <?php $paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
    $args = array(
        'post_type'   => 'post',
        'paged'       => $paged,
        'meta_key'    => 'votes_count', 
        'orderby'     => 'meta_value_num', 
        'order'       => 'DESC',
        'post_status' => 'publish'
    ); 
    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) :
        while ( $the_query->have_posts() ) : $the_query->the_post();
            get_template_part( 'public/partials/template/loop' );
        endwhile; ?> 
        <li class="numeration">
            <div class="paginavi">
                 <?php YESPLEASE_Add_Theme_Support::yesplease_pagination(); ?>  
            </div>
        </li>
    <?php endif;?>                  
</ul>

Solution

  • You can use meta_query Try this below code.

    $args = array(
        'post_type'   => 'post',
        'paged'       => $paged,
        'meta_key'    => 'votes_count', 
        'orderby'     => 'meta_value_num', 
        'order'       => 'DESC',
        'post_status' => 'publish',
        'meta_query' => array(
            array(
                'key' => 'votes_count',
                'value'   => array(''),
                'compare' => 'NOT IN'
            )
        )
    );