How do I filter posts by most liked/voted?

So it's pretty simple, there's way to filter posts by date, random, etc.. How do I filter it to show the posts with the most likes/votes? Is there a specific php code I can add to the post query thing?

This is how my posts are pulled:

<?php $i = 0; while (have_posts()) : the_post(); $i++; ?>

I add this to make it random..

<?php query_posts('orderby=rand'); $i = 0; while (have_posts()) : the_post(); $i++; ?>

How would I edit that to show it with the top liked posts at the top? Throwing out the random thing.. Just showing how I know how to edit it already..

Thanks in advance.

  • aristath

    Hello there @Chippy, i hope you're well today!

    You can use the wdpv_popular() function to display posts sorted by votes.

    // display 5 highest rated posts on the current blog.
    // display 3 highest rated posts on the current blog.
    // display 5 highest rated posts on entire network.
    wdpv_popular(5, true);
    // display 10 highest rated posts on entire network.
    wdpv_popular(10, true);

    I hope that helps!


  • Hoang Ngo

    Hi @Chippy,,

    I hope you are well today and I'm sorry for the delay.

    Please add this code to your theme functions.php or use mu-plugins

    This will sort the post by the most post vote. You can base on this code and have some customize to fit with your need.

    add_filter('posts_results', 'inject_post_vote_query', 10, 2);
    function inject_post_vote_query($posts, $q)
        if ($q->is_main_query()) {
            global $wpdb;
            $clone = $posts;
            foreach ($clone as &$post) {
                $sql = "SELECT COUNT(id) as count FROM " . $wpdb->prefix . 'wdpv_post_votes WHERE post_id=%d AND blog_id=%d';
                $sql = $wpdb->prepare($sql, $post->ID, get_current_blog_id());
                $count = $wpdb->get_var($sql);
                $post->post_vote = $count;
            usort($clone, '_inject_post_vote_query');
           return $clone;
        return $posts;
    function _inject_post_vote_query($a, $b)
        return $a->name > $b->name;

    If you have any issues please don't hesitate to let us know so we can assist

    Best regards,
    Hoang Ngo

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.