phpdatabasewordpressmeta-key

Order custom post types in WordPress by the meta_value of another plugin


I've got a List of custom post types which I am displaying on my site. Additionally to those post types, I added a plugin to my WordPress which allows me to add a thumbs up rating system to each post type, so that it looks like this:

https://i.imgur.com/jXR26i5.jpg

The code for looks like this:

<?php
/* The custom post types query */
    $query = new WP_Query( array(
        "post_type" => "motto",
        "order" => "ASC",
    ));
    while($query -> have_posts()) : $query -> the_post();
?>

/* Container with the ratings from the plugin + each post type */
<div id="motto-container">
    <?=function_exists('thumbs_rating_getlink') ? thumbs_rating_getlink() : ''?>
    <h3 class="abimottos">
        <?php echo get_post_meta($post->ID, 'motto_titel', true); ?>
    </h3>
</div>

I've got a list of these custom posts + their ratings, and of course each post has an individual rating and I want to order my custom post types after the value of those ratings. How could I archive that?

I know that the meta_key for the ratings is _thumbs_rating_up (since I've already modified the value with the ARI Adminer plugin), can I somehow use this meta_key to order the custom post types after the meta_value of the ratings?

I'm pretty new to PHP and databases.


Solution

  • You are already using WP_Query to get the posts, so you can specify the meta_key to sort by in the $args array, e.g.

    $query = new WP_Query( array(
        'post_type'  => 'motto',
        'meta_key'   => 'thumbs_rating_up',
        'orderby'    => 'thumbs_rating_up',
        'order'      => 'DESC'
    ));
    

    Note that you need to include the key name in both meta_key and orderby. I also assume you want to sort in descending order to show the highest ratings first.

    Ref: Wordpress Codex for WP_Query

    Also, a note on the meta_key:
    meta_keys prefixed with an underscore are private and hidden from the custom fields, so normally you would use the version without an underscore. This might not be the case here because I assume the rating can't be changed in the admin, but just make sure that the meta_key you need to use is actually _thumbs_rating_up and not thumbs_rating_up.