Adding Two Short Code Functions to WordPress: Top Posts By Number of Comments and Top Posts by Ratings


The wordpress shortcode is a great feature that we can easily add via the add_shortcode function. This post introduces two shortcode functions in WordPress to get the top 10 posts by the comment count (show_top_posts_by_comments) or by the ratings (show_top_posts_by_rating)

WordPress shortcode: Top Posts By Number of Comments

The shortcode show_top_posts_by_comments requires four parameters:

  • “year” is optional, if specified, will only return the posts of the year, otherwise, all the posts will be considered.
  • “type” is the HTML list type, default is ul (unordered list), you can specify “ol” to make it a ordered list.
  • “urltype” default is the short, it can be “full”, this changes the permlink format. You might want to customize the permlink type, if it is not what you want, you can do this easily by changing the corresponding line (you need some programming skills for this)
  • “count” default is 10 posts to return.

Here is the code, to add in the functions.php of your wordpress theme.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function show_top_posts_by_comments_func($atts) {
    global $wpdb;
    extract(shortcode_atts(
        array(
            'year' => '',
            'type' => 'ol',
            'urltype' => 'short',
            'count' => '10'
    ), $atts));
    $query = "
        SELECT 
            `id`, 
            `post_name`,
            `post_title` 
        FROM 
            `$wpdb->posts`
        WHERE 
            `post_type` = 'post' and 
            `post_status` = 'publish'  
    ";
    if ($year) {
        $query .= " and date_format(`post_date_gmt`, \"%Y\") = '$year' ";
    }
    $query .= "
        ORDER BY
            `comment_count` DESC
        LIMIT $count
    ";
    $result = $wpdb->get_results($query);
    $ans = "<$type>";
    if ($result) {
        foreach ($result as $post) {
            if ($urltype === "short") {
                $ans .= "<li><a title='".htmlentities($result->title, ENT_QUOTES)."' href='/archives/".($post->id)."'>".$post->post_title."</a></li>";
            } else {
                $ans .= "<li><a title='".htmlentities($result->title, ENT_QUOTES)."' href='/". $post->post_name . "/'>".$post->post_title."</a></li>";
            }
        }
    }
    $ans .= "</$type>";
    return $ans;
}
 
add_shortcode('show_top_posts_by_comments', 'show_top_posts_by_comments_func');
function show_top_posts_by_comments_func($atts) {
    global $wpdb;
    extract(shortcode_atts(
        array(
            'year' => '',
            'type' => 'ol',
            'urltype' => 'short',
            'count' => '10'
    ), $atts));
    $query = "
        SELECT 
            `id`, 
            `post_name`,
            `post_title` 
        FROM 
            `$wpdb->posts`
        WHERE 
            `post_type` = 'post' and 
            `post_status` = 'publish'  
    ";
    if ($year) {
        $query .= " and date_format(`post_date_gmt`, \"%Y\") = '$year' ";
    }
    $query .= "
        ORDER BY
            `comment_count` DESC
        LIMIT $count
    ";
    $result = $wpdb->get_results($query);
    $ans = "<$type>";
    if ($result) {
        foreach ($result as $post) {
            if ($urltype === "short") {
                $ans .= "<li><a title='".htmlentities($result->title, ENT_QUOTES)."' href='/archives/".($post->id)."'>".$post->post_title."</a></li>";
            } else {
                $ans .= "<li><a title='".htmlentities($result->title, ENT_QUOTES)."' href='/". $post->post_name . "/'>".$post->post_title."</a></li>";
            }
        }
    }
    $ans .= "</$type>";
    return $ans;
}

add_shortcode('show_top_posts_by_comments', 'show_top_posts_by_comments_func');

To use it in a post or page, you can do this:

1
2
// add [ before and ] after
show_top_posts_by_comments urltype="full" count="10" year="2023" type="ol"
// add [ before and ] after
show_top_posts_by_comments urltype="full" count="10" year="2023" type="ol"

And it produces the following (top 10 posts by comments)

  1. How to Solve 403 Forbidden Error (Denied by Referer ACL) when Downloading Weibo Video?
  2. 4 Reasons to Upgrade the CloudFlare Free Plan to Pro
  3. What is LLVM? (Low-Level Virtual Machine)
  4. Teaching Kids Programming - Max Number of Connected Components in a Directed Graph (Detonate the Maximum Bombs) via Recursive Depth First Search Algorithm
  5. Teaching Kids Programming - Check if There is a Path With Equal Number of 0's And 1's (Breadth First Search Algorithm)
  6. Teaching Kids Programming - Minimum Number of Arrows to Burst Balloons (Greedy Algorithm)
  7. How to Transfer Domain From Namesilo to CloudFlare Registra?
  8. Introduction to Order Book, HFT (High Frequency Trading) and Simple Strategy: Buy Low Sell High
  9. Teaching Kids Programming - Maximum Count of Positive Integer and Negative Integer in Sorted Array
  10. Common Azure Kubernetes Services AKS Commands (Cheet Sheet)


Remember, if you don’t specify “year” parameter, the top 10 posts of all time will be returned.

WordPress shortcode: Top Posts By Ratings

Similarly, you can call the shortcode show_top_posts_by_rating to get the top posts by rating. This function has same parameters/usages, so see above example.

Here is the PHP code to add the shortcode function to return the top posts by ratings, which needs to be inserted into the functions.php of the wordpress theme (child themes preferred).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function show_top_posts_by_rating_func($atts) {
    global $wpdb;
    extract(shortcode_atts(
        array(
            'year' => '',
            'type' => 'ol',
            'urltype' => 'short',
            'count' => '10'
    ), $atts));
    $query = "
    SELECT 
        `p`.`ID` as `id`, 
        `p`.`post_title` as `post_title`,
        `p`.`post_name` as `post_name`,
        `visitor_votes` + `user_votes` as `total_votes`, 
        `visitor_votes`, 
        `user_votes`  
    FROM  
        `".$wpdb->prefix."gdsr_data_article` as `da` 
        INNER JOIN `$wpdb->posts` as `p` ON `da`.`post_id` = `p`.`ID` 
    WHERE
        `p`.`post_type` = 'post' and 
        `p`.`post_status` = 'publish'  
    ";
    if ($year) {
        $query .= " and date_format(`post_date_gmt`, \"%Y\") = '$year' ";
    }    
    $query .= "
        HAVING
        `total_votes` > 0
        ORDER BY
        `total_votes` DESC
        LIMIT $count
    ";
    $result = $wpdb->get_results($query);
    $ans = "<$type>";
    if ($result) {
        foreach ($result as $post) {
            if ($urltype === "short") {
                $ans .= "<li><a title='".htmlentities($result->title, ENT_QUOTES)."' href='/archives/".($post->id)."'>".$post->post_title."</a></li>";
            } else {
                $ans .= "<li><a title='".htmlentities($result->title, ENT_QUOTES)."' href='/". $post->post_name . "/'>".$post->post_title."</a></li>";
            }
        }
    }
    $ans .= "</$type>";
    return $ans;
}
 
add_shortcode('show_top_posts_by_rating', 'show_top_posts_by_rating_func');
function show_top_posts_by_rating_func($atts) {
    global $wpdb;
    extract(shortcode_atts(
        array(
            'year' => '',
            'type' => 'ol',
            'urltype' => 'short',
            'count' => '10'
    ), $atts));
    $query = "
    SELECT 
        `p`.`ID` as `id`, 
        `p`.`post_title` as `post_title`,
        `p`.`post_name` as `post_name`,
        `visitor_votes` + `user_votes` as `total_votes`, 
        `visitor_votes`, 
        `user_votes`  
    FROM  
        `".$wpdb->prefix."gdsr_data_article` as `da` 
        INNER JOIN `$wpdb->posts` as `p` ON `da`.`post_id` = `p`.`ID` 
    WHERE
        `p`.`post_type` = 'post' and 
        `p`.`post_status` = 'publish'  
    ";
    if ($year) {
        $query .= " and date_format(`post_date_gmt`, \"%Y\") = '$year' ";
    }    
    $query .= "
        HAVING
        `total_votes` > 0
        ORDER BY
        `total_votes` DESC
        LIMIT $count
    ";
    $result = $wpdb->get_results($query);
    $ans = "<$type>";
    if ($result) {
        foreach ($result as $post) {
            if ($urltype === "short") {
                $ans .= "<li><a title='".htmlentities($result->title, ENT_QUOTES)."' href='/archives/".($post->id)."'>".$post->post_title."</a></li>";
            } else {
                $ans .= "<li><a title='".htmlentities($result->title, ENT_QUOTES)."' href='/". $post->post_name . "/'>".$post->post_title."</a></li>";
            }
        }
    }
    $ans .= "</$type>";
    return $ans;
}

add_shortcode('show_top_posts_by_rating', 'show_top_posts_by_rating_func');

To use it in a post or page, you can do this:

1
2
// add [ before and ] after
show_top_posts_by_rating urltype="full" count="10" year="2023" type="ol"
// add [ before and ] after
show_top_posts_by_rating urltype="full" count="10" year="2023" type="ol"

And it produces the following (top 10 posts by comments)

  1. How ChatGPT Impacts UGC (User Generate Content)?
  2. TRON Blockchain: How to Send the USDT (TRC-20) Transacton using Python tronpy?
  3. What are the Differences between uBPF and eBPF?
  4. How to Extract a Domain Name from a Full URL in BASH?
  5. Teaching Kids Programming - Smallest Number With Given Digit Product (Greedy Factorization Algorithm)
  6. Introduction to Ledger Virtual Crypto Card
  7. Can the Kids Beat This Simple Chinese Chess AI?
  8. Teaching Kids Programming - Check if There is a Path With Equal Number of 0's And 1's (Maze, Recursion, Memoization, Dynamic Programming)
  9. Teaching Kids Programming - Minimum Number of Arrows to Burst Balloons (Greedy Algorithm)
  10. Manual RAID-1 using Two 18TB USB External Hard Drive (HDD)

Relevant Posts of the Year

Wordpress is King!

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
a WordPress rating system
881 words
Last Post: How to Check Balances of a Bitcoin (BTC) Wallet Address via NodeJs or Python?
Next Post: How to Transfer Domain From Namesilo to CloudFlare Registra?

The Permanent URL is: Adding Two Short Code Functions to WordPress: Top Posts By Number of Comments and Top Posts by Ratings

Leave a Reply