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

Got an idea? We'll turn it into reality.

Tell us what you're building, what's broken, or what numbers need to move. We'll come back within one business day with a short plan — no long decks, no sales calls without purpose.

Response time: First reply within 1 business day on 100% of messages.
Transparent scope: Fixed proposals with weekly check-ins & live task tracking.
Ship-ready builds: Every engagement leaves behind documented, transferable work.
Long-term partners: Ongoing retainers for support, SEO, ads, and content.