WordPress Multisite: How to show popular post acrosee the network (without any plugin)

WordPress Multisite is a very popular platform now a days for owning of a series of blog site. Well, it can be any e-commerce market. You can easily develop a etsy ptsy style market with MarketPress. Also you can charge your store owner for using your platform as well themes and plugins using Pro Sites. It’s fun, huh?

Sometimes we need to show popular posts across our site. That can be easily done. But what if you want to grab popular posts across the network in multisite? Well, that’s not also a rocket science. We will see today how to get popular posts based on comment count. It’s also possible to get based on page views, that’s in some other day :)

First of all let’s see how to get popular posts in a single wordpress installation. You can add those codes in your functions.php in the theme, if you think your theme won’t be changed. Otherwise mu-plugins is the best solution.

[php]
function get_popular_posts() {
global $wpdb;
$posts = $wpdb->get_results(“SELECT * FROM {$wpdb->prefix}posts WHERE post_type=’post’ AND post_status=’publish’ AND comment_count != 0 ORDER BY comment_count DESC LIMIT 10″); /*We don’t want to include those posts that has no comments yet, so comment_count != 0 */
$html = ‘

‘;
return $html;
}
[/php]

Then you can call the function anywhere you like – header, footer, sidebar etc.
[php]
echo get_popular_posts();
[/php]

Now, if we want to get popular posts across the network, we need to use the above function with a little tricks :) Let’s take a look:

[php]
function get_popular_posts() {
global $wpdb;

$blogs = $wpdb->get_results( “SELECT blog_id FROM {$wpdb->blogs} WHERE blog_id != {$wpdb->blogid} AND site_id = ‘{$wpdb->siteid}’ AND spam = ‘0’ AND deleted = ‘0’ AND archived = ‘0’ order by blog_id”, ARRAY_A);
array_unshift($blogs, 1); /*Including parent blog in the array*/
$html = ‘

    ‘;
    foreach($blogs as $blog) {
    switch_to_blog( $blog[ ‘blog_id’ ] );
    $posts = $wpdb->get_results(“SELECT * FROM {$wpdb->prefix}posts WHERE post_type=’post’ AND post_status=’publish’ AND comment_count != 0 ORDER BY comment_count DESC LIMIT 10″);
    foreach($posts as $post) {
    $html .= ‘

  • ID).’”>’.$post->post_title.’
  • ‘;
    }
    }
    $html .= ‘

‘;
return $html;
}
[/php]

Then you can call the function anywhere you like – header, footer, sidebar etc.
[php]
echo get_popular_posts();
[/php]

Easy pissy, nah? ;)

Leave a Reply

Your email address will not be published. Required fields are marked *