WordPress   

WP Query to sort posts based on the numeric value of a custom field

Following WP Query can be used to get posts in descending order on the basis of the numeric value of the custom field rating. You can change the order of the posts from descending to ascending by simply changing DESC to ASC.

$args = array(
    'post_type' => 'posts',
    'posts_per_page' => 10,
    'meta_key' => 'rating',	
    'orderby' => 'meta_value_num',	
    'order' => 'DESC',
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
    while( $query->have_posts() ): $query->the_post();
        echo the_title(); 
    endwhile; 
    wp_reset_postdata();
else :
    echo 'No posts found';
endif;

 

 

Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us