Try Tuts+ Premium, Get Cash Back!
A Featured Blog Plugin for WordPress Multisite

A Featured Blog Plugin for WordPress Multisite

Tutorial Details
  • Program: WordPress
  • Difficulty: Intermediate
  • Estimated Completion Time: 45 min

WordPress is become one of the most popular open source blogging platforms. As of WordPress 3.0 WordPressMU also became a part of WordPress. The WordPress Multisite feature allows you to create a network of sites which run from the same WordPress installation. So one can upload a plugin or a theme to the installation and it will be available to all the sites on that WordPress network.

In this article we are going to see how to create a Featured Blog plugin which creates a widget and shortcode to display a Featured Blog on a WordPress Multisite installation.


Step 1 WordPress Multisite Installation

In case you don’t have the WordPress Multisite installation done already you can download the latest WordPress installation from WordPress.org. This article lists through the steps for creating a WordPress Multisite installation. You can follow the steps to successfully install WordPress Multisite instance on your server.


Step 2 Creating a Network Plugin

Now we are going to create a network plugin called as featured blog. In your wp-content/plugins folder create a directory called featuredblog. Inside that directory create a file featuredblog.php with the following content:

/*
Plugin Name: Featured Blog
Plugin URI: http://wp.tutsplus.com/tutorials/plugins/a-featured-blog-plugin-for-wordpress-multisite/
Description: This plugin helps you display featured blogs on you multisite installation
Author: Abbas
Version: 0.1
Author URI: http://wp.tutsplus.com/author/AbbasSuterwala/
Network: true
*/

This should create a network plugin for us as the Network: true is used and we should be able to see this plugin in the network admin plugin list as follows. Now we can activate this plugin for the whole network from the network admin.


Step 3 Creating Functions to Fetch Posts From Different Blogs

Function for Getting the Post From a Blog

function Featured_blog_posts_for_blog($blog_id,$numberofpost) {

	$output = '';
	wp_reset_query();
	switch_to_blog($blog_id);

	global $post;
	$my_query = new WP_Query('order=DSC&posts_per_page='.$numberofpost);
	while ($my_query->have_posts()) :
		$my_query->the_post();
		$output .='<li class="post_link"><a href="'.get_permalink(). '" rel="bookmark">'.get_the_title().'</a> </li>';
	endwhile; 

	restore_current_blog();

	return $output;
}

In this function we take in the $blog_id and the number of posts we want to fetch. In this function the first thing we do is switch to the blog which is passed to the function. This is done through the WordPress function switch_to_blog. For more details check out href="http://codex.wordpress.org/WPMU_Functions/switch_to_blog">switch_to_blog in the WordPress Codex. Then we create a query depending on the number of posts which are to be displayed using the WP_Query. In case you are not already familiar with it, you can check out WP_Query in the WordPress Codex too. Then we loop through the results of WP_Query and add in a list of the post title and the post name. Then we use the restore_current_blog function to restore to the blog which was there before we switched blogs.

Function to Get Post for a List of Blogs

function Featured_blog_posts_for_specified_blogs($commaseparatedblogids,$numberofpost) {

	$commaseparatedblogids = str_replace (" ", "", $commaseparatedblogids);

	$output = '';

	if(strlen($commaseparatedblogids) > 0 ) {

		$blogids = explode(',',$commaseparatedblogids);
		
		foreach($blogids as $blogid) {

			$blog_details = get_blog_details($blogid);
			$output .='<li class="blog_link"><a href="'.$blog_details->siteurl. '" rel="bookmark">'.$blog_details->blogname.'</a> </li>';
			$output.='<ul>'.Featured_blog_posts_for_blog($blogid,$numberofpost).'</ul>';
		}
	}

	return $output;
}

This function takes a list of comma separated blog IDs and the number of posts we want for each blog as input. In this function we remove any white space present in the comma separated blog list. Then it is exploded on the basis of the comma and we loop through each blog ID. Then using the previous function Featured_blog_posts_for_blog we fetch the posts for each blog. The result is created in a list and returned by this function.


Step 4 Creating a Shortcode

Now we are going to create a shortcode to display the featured blogs.

function Featured_blog_shortcode($atts, $content = null) {

	extract(shortcode_atts(array('blogids' => '', 'numberofpost' => '3'), $atts));
	
	if(strlen($blogids) > 0 )
		 return '<ul>' .  Featured_blog_posts_for_specified_blogs($blogids,$numberofpost) . '</ul>';
	
}
add_shortcode('FEATURED_BLOG', 'Featured_blog_shortcode');

In the function Featured_blog_shortcode the arguments from the shortcode are passed. Then using the function shortcode_atts we merge the passed arguments with default values. For more details read the href="http://codex.wordpress.org/Function_Reference/shortcode_atts">shortcode_atts page in the WordPress Codex. Then we pass the comma separated blog list to the function Featured_blog_posts_for_specified_blogs which fetches the post from those blogs and returns a list.


Step 5 Using the ShortCode

To use the shortcode now we will create a new post, we will create a new post called “Featured Blogs” and then add the shortcode in its content as [FEATURED_BLOG blogids="3,1" numberofpost="2"], see also in the screen shot.

If we see the post preview now it will be seen as follows showing the featured blogs.


Step 6 Creating a Featured Blog Widget

To create a widget we will have to create a class that inherits from WP_Widget. The code for the widget is as follows:

class FeaturedBlogWidget extends WP_Widget {

	function FeaturedBlogWidget() {
		// widget actual processes
		$widget_ops = array('classname' => 'FeaturedBlogWidget', 'description' => 'Widget for featured blog' );
		$this->WP_Widget('FeaturedBlogWidget', 'FeaturedBlogWidget', $widget_ops);
	}

	function form($instance) {
		// outputs the options form on admin
		 $defaults = array( 'title' => 'Featured Blogs', 'blogids' => '' , 'numberofpost' => '3');
		 $instance = wp_parse_args( (array) $instance, $defaults );
		 
		 ?>
		 <p>
		 <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php echo 'Title:'; ?></label>
		 <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" class="widefat" />
		 </p>
		 <p>
		 <label for="<?php echo $this->get_field_id( 'blogids' ); ?>"><?php echo 'Blog Ids: Separated By comma' ; ?></label>
		 <input id="<?php echo $this->get_field_id( 'blogids' ); ?>" name="<?php echo $this->get_field_name( 'blogids' ); ?>" value="<?php echo $instance['blogids']; ?>" class="widefat" />
		 </p>
		 <p>
		 <label for="<?php echo $this->get_field_id( 'numberofpost' ); ?>"><?php echo 'Number of posts per blog' ; ?></label>
		 <input id="<?php echo $this->get_field_id( 'numberofpost' ); ?>" name="<?php echo $this->get_field_name( 'numberofpost' ); ?>" value="<?php echo $instance['numberofpost']; ?>" class="widefat" />
		 </p>

		<?php
		 
	}

	function update($new_instance, $old_instance) {
		// processes widget options to be saved

		 $instance = $old_instance;
		 $instance['title'] = strip_tags( $new_instance['title'] );
		 $instance['blogids'] = $new_instance['blogids'];
		 $instance['numberofpost'] = $new_instance['numberofpost'];
		 return $instance;
	}

	function widget($args, $instance) {
		// outputs the content of the widget
		 extract( $args );
		 $title = apply_filters('widget_title', $instance['title'] );
		 echo $before_widget;
		 if ( $title )
			echo $before_title . $title . $after_title;
			
		 echo '<ul>';
		 echo Featured_blog_posts_for_specified_blogs($instance['blogids'],$instance['numberofpost']);
 		 echo '</ul>';
		 echo $after_widget;
	}

}

function Featured_blog_widget_init() {

	// Check for the required API functions
	if ( !function_exists('register_widget') )
		return;
	
	register_widget('FeaturedBlogWidget');
}
add_action('widgets_init', 'Featured_blog_widget_init');

In the constructor below

function FeaturedBlogWidget() {
	// widget actual processes
	$widget_ops = array('classname' => 'FeaturedBlogWidget', 'description' => 'Widget for featured blog' );
	$this->WP_Widget('FeaturedBlogWidget', 'FeaturedBlogWidget', $widget_ops);
}

In this we add the name and the description for the widget.

In the form function

function form($instance) {
	// outputs the options form on admin
	$defaults = array( 'title' => 'Featured Blogs', 'blogids' => '' , 'numberofpost' => '3');
	$instance = wp_parse_args( (array) $instance, $defaults );

	?>
	<p>
	<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php echo 'Title:'; ?></label>
	<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" class="widefat" />
	</p>
	<p>
	<label for="<?php echo $this->get_field_id( 'blogids' ); ?>"><?php echo 'Blog Ids: Separated By comma' ; ?></label>
	<input id="<?php echo $this->get_field_id( 'blogids' ); ?>" name="<?php echo $this->get_field_name( 'blogids' ); ?>" value="<?php echo $instance['blogids']; ?>" class="widefat" />
	</p>
	<p>
	<label for="<?php echo $this->get_field_id( 'numberofpost' ); ?>"><?php echo 'Number of posts per blog' ; ?></label>
	<input id="<?php echo $this->get_field_id( 'numberofpost' ); ?>" name="<?php echo $this->get_field_name( 'numberofpost' ); ?>" value="<?php echo $instance['numberofpost']; ?>" class="widefat" />
	</p>

	<?php

}

We create three text fields for

  • The title of the widget
  • The blog list
  • The number of posts per blog to be displayed

Here we merge the default values for the widget with the instance values using the function wp_parse_args. For more details on href="http://codex.wordpress.org/Function_Reference/wp_parse_args">wp_parse_args view the page in the WordPress Codex. The widget in the admin should now look as follows.

In the updated function

function update($new_instance, $old_instance) {
	// processes widget options to be saved

	 $instance = $old_instance;
	 $instance['title'] = strip_tags( $new_instance['title'] );
	 $instance['blogids'] = $new_instance['blogids'];
	 $instance['numberofpost'] = $new_instance['numberofpost'];
	 return $instance;
}

We update the title, blogids and numberofpost function when save is clicked by coping it in the instance. In the widget function

function widget($args, $instance) {
	// outputs the content of the widget
	extract( $args );
	$title = apply_filters('widget_title', $instance['title'] );
	echo $before_widget;
	if ( $title )
		echo $before_title . $title . $after_title;

	echo '<ul>';
	echo Featured_blog_posts_for_specified_blogs($instance['blogids'],$instance['numberofpost']);
	echo '</ul>';
	echo $after_widget;
}

In this function we get the values saved for the widget instance. The title is used as the title of the widget. We get the values for the blog list and the number of posts and pass it to the function Featured_blog_posts_for_specified_blogs which returns the list of posts from each blog.

We need to register this widget

function Featured_blog_widget_init() {

	// Check for the required API functions
	if ( !function_exists('register_widget') )
		return;
	
	register_widget('FeaturedBlogWidget');
}
add_action('widgets_init', 'Featured_blog_widget_init');

To register the widget we use the function register_widget in the function Featured_blog_widget_init which is added to the action hook ‘widgets_init‘.

The output of the widget will look as follows.


Conclusion

WordPress Multisite is a great platform to create a network of sites. In this plugin we saw how we can create a network plugin to display featured blogs. By creating such plugins we can enhance the WordPress Multisite platform and also provide the extra features which we need for our site network. There are also a lot of open source plugins for WordPress Multisite.

So have fun using WordPress Multisite for your network of sites!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://kovshenin.com Konstantin Kovshenin

    Sweet! Though I have a couple very important aspects you forgot to mention.

    First mistake is the use of the $blog_id in your first code snippet. $blog_id is a global variable used by WordPress to indicate the current blog ID, and can be retrieved with get_current_blog_id which uses that global. Even if it seems to work at first sight, you’ll notice some really strange things happening behind the scenes. Your second snippet looks better, though I’d suggest $which_blog instead, to avoid confusion.

    Second problem is the performance impact when using switch_to_blog, because each call is expensive. Suppose I’m viewing an archive of all your posts tagged “featured-blogs”, that’s 10 “switch to blogs” per page and a few more in your sidebar. Page caching can save your life, but you shouldn’t rely on it. I’d suggest caching the results with transients for several hours.

    The other route would be to simply use RSS feeds and get transient caching for free.

    ~ Konstantin

    • http://wp.envato.com/ Japh Thomson
      Staff

      Hey Konstantin, great suggestions, thank you! :)

    • http://www.designbigdreams.com/ Anthony

      So, do you recommend using this plugin. I ask because you bring up concerns, so I wasn’t sure if the code will be updated per your suggestions… I have been looking for something like this for about a year, and I want a reliable solution.

      Thank you,
      Anthony

  • http://www.feed2need.com Abdelhadi Touil

    Very nice and clear tutorial! I’ll use this plugin in the futur. Thanks very much.

  • http://www.ellahworks.com Rowela Alzona

    This is awesome, I will soon try this one for my upcoming project. Thank you for sharing…..

  • Pingback: Compromised WordPress sites serving client-side exploits and malware | Open Knowledge

  • Pingback: A Featured Blog Plugin for WordPress Multisite | Shadowtek | Hosting and Design Solutions

  • Pingback: Plugin für Worpress Multisite – Featured Blog Plugin « arlivre.eu

  • Sebastien

    Thanks for that plugin. It works perfectly.
    In order to have all the blogs of my network, i have added these lines :

    $aBlogs = get_last_updated();
    $cBlogids = “”;
    foreach($aBlogs as $aBlog) {
    $cBlogids.=”,”.$aBlog[blog_id];
    }
    $instance['blogids'] = substr($cBlogids,1); // line A
    $commaseparatedblogids = substr($cBlogids,1); // line B

    Line A has to be there if I want to include this in function Featured_blog_posts_for_specified_blogs(), right after $output = ”;
    Line B has to be there if I want to include this in function form(), after the line $instance = wp_parse_args( (array) $instance, $defaults );

    Case Line A, allow me not to think about the number of blogs I have to deal with.
    Case Line B will just prefill the list of blogs, comma separated.

    Get_last_updated does count only the blogs marked as “public”. If you dont want to see some blogs, just uncheck this “Public” case.

    Thanks again.

  • ajnabi insan

    I’have 2 questions.
    1) how can we add pictures thumb with each post?
    and
    2) how can we add specific category of a specific blog?? for example if i have a sub blog “News”. this blog too many categories like national news, international news, sports news etc. Now I want to show on “Main Home Blog” only “sports news” from the blog “news”.

    Please help me regarding this.