• Hey guys,

    I’m running an entertainment site, and we also do film/game/music reviews. They all contain a custom field with a numerical value of 0.5-5 as an overall score.

    The first question is how would I go about displaying say, 10 top reviews in general (each category), in order of highest to lowest?

    The second is how would I do the above but for a specific category? eg having the 10 best film reviews?

    Thanks in advance!
    Ben

Viewing 2 replies - 1 through 2 (of 2 total)
  • I’m assuming you plan on displaying the posts with a custom query in a custom page template. To order a query by a numeric custom field, you can try using wp_query()‘s meta_key and orderby arguments.

    https://codex.www.ads-software.com/Class_Reference/WP_Query

    For example:

    $args = array(
        'meta_key' => 'my_key',
        'orderby' => 'meta_value_num'
    );
    
    $my_query = new WP_Query( $args );
    
    while ( $my_query->have_posts() ) { $my_query->the_post();
        /* Your post loop */
    }

    If you want the query to only return posts in certain categories, you can add the category__in argument:

    $args = array(
        'category__in' => array( 27, 76 ),
        'meta_key' => 'my_key',
        'orderby' => 'meta_value_num'
    );

    Edit: I should also mention that you can specify the number of posts to show with posts_per_page, and if you want pagination to work you have to add the paged argument:

    $args = array(
        'posts_per_page' => 10,
        'paged' => get_query_var( 'page' ),
        'category__in' => array( 27, 76 ),
        'meta_key' => 'my_key',
        'orderby' => 'meta_value_num'
    );

    Thanks for this very useful post. Sorry if I’m renewing an older thread, but question — where does one add this code? In the archive.php template file?

    And then how does one link to that page? I’d like to create a site header with direct links to all posts with the meta value Color = x (black, blue, etc).

    Thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Sort Posts by Category and Custom Field Meta Value’ is closed to new replies.