skip to Main Content

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>

2

Answers


  1. It only shows the ones that have the value because that is precisely what you’re asking it to do.

    All I can think of to counter that is to make it a required field in the admin panel, or finding some other way of including it in the post object using, for example, ACF.

    ACF is the most powerful plugin there is on the topic of adding custom fields that are easy to access in all post types, with extensive and easy-to-read documentation. By using ACF you can make it a required value in the post edit screen, or you can make it default to an actual value, like 0 instead of NULL.

    Login or Signup to reply.
  2. 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'
            )
        )
    ); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search