I'm trying to add a "Highlighted" section for each category on my website. This will be located in a page, using a shortcode. I'm going to add a new post metadata key which will be a number from 0 to 100. Each "Highlighted" section will list the posts in that category which have a score higher than 50, in descending order of score.

Looking in the WordPress Codex, I saw that get_posts accepts "meta_key" and "meta_value" as arguments. However, they seem to be specific values, whereas I would like to add a "greater than 50" condition for the "meta_key".

How would one get those "greater than 50" posts?


This kind of meta query in WP_Query() or get_posts():

'meta_query' => [
        'key'     => 'score',
        'value'   => 50,
        'type'    => 'numeric',
        'compare' => '>=',

would generate the following SQL WHERE part:

wp_postmeta.meta_key = 'score' AND CAST(wp_postmeta.meta_value AS SIGNED) >= '50' 

This kind of ordering:

'orderby'  => [ 
    'meta_value_num' => 'DESC', 
    'title'          => 'ASC' 

would generate:

ORDER BY wp_postmeta.meta_value+0 DESC, wp_posts.post_title ASC 

If we use the syntax defined here, with the meta query array index as score_clause, then

'orderby'  => [ 
    'score_clause'  => 'DESC', 
    'title'         => 'ASC' 

would generate:

ORDER BY CAST(wp_postmeta.meta_value AS SIGNED) DESC, wp_posts.post_title ASC 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.