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 Professional Support for Your Website Problems?

Whether you're facing website issues or struggling with code implementation, our team is here to assist. Hire us to get your website back on track.

Hire Us