Advertisement
Plugins

Creating a WordPress Network Widget

by

In this tutorial, we are going to create a widget that will display sites from a WordPress Network of sites. This short tutorial will show you how simple it is, to create a widget and use it to navigate to different network sites.


Step 1 Adding the Base for the Widget

Assuming that you have already set up a Network of sites, we will begin by creating a file mynetwork.php. Add the following code for the base to extend the WordPress Widget Class.

/*
Plugin Name: Your Plugin Name Here
Plugin URI: http://yourpluginsite.com
Description: This displays your Blogs in your WP Network
Author: The Author Name Here
Version: 1.0.0
Author URI: http://theauthoraddress.com
*/
class MyNetwork_Widget extends WP_Widget {

	public function __construct() {
		// widget actual processes
	}

	public function form( $instance ) {
		// outputs the options form on admin
	}

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

	public function widget( $args, $instance ) {
		// outputs the content of the widget
	}
}
add_action( 'widgets_init', create_function( '', 'register_widget( "mynetwork_widget" );' ) );

"The function add_action( 'widgets_init','') is used to register our widget"


Step 2 Writing the Construct Function

Now that we have the base of our widget, let's start adding actual functionalities to it. We'll start by adding a new object attribute called blogs. This attribute will be used as an array to hold the list of registered blogs on your site.

class MyNetwork_Widget extends WP_Widget {
	public $blogs = null;

Now we will add some small snippets to our __construct function. First we will assign an array of blogs to the object attribute by using the WordPress function get_blog_list. Any time we plan to reference the array, we simply use $this->blogs.

public function __construct() {
	$this->blogs = get_blog_list( 0, 'all' );

Lastly, we'll call the parent constructor function and add some information about our widget. The function takes a Base ID(string), Name(string), Options(array) and Control Options(array). This information will will be displayed in the widget panel.

	parent::__construct(
		'mynetwork_widget', // Base ID
		'MyNetwork_Widget', // Name
		array(
			'description' => __( 'Display List of Blogs in Site Network', 'text_domain' )
		)
	);
}

Step 3 Writing the Form Function

In this step we will create the widget form found in the administrator. Our form will have an Image Url field for each blog on the site. The URL field will hold a thumbnail of the site being referenced.

Looping Through Blogs

The first thing we do is create a foreach loop that will loop through each site's blogs created on your site. The loop does not include the blog name, so for this purpose we use the get_blog_details function. The function takes the blog id and can return Blog Name, ID, Post Count, Path and more. We will add the blog name above each URL field. If you you look closely, you will see that our get_field_id function uses the blog_id, this will make our name tag look like this image-1 which will be important for us in our other functions.

	public function form( $instance ) {
		// outputs the options form on admin
		foreach ($this->blogs AS $blog) {
			$image =  $instance['image-'.$blog['blog_id']];
			?>
			<p>
				<label><strong><?php echo get_blog_details($blog['blog_id'])->blogname; ?></strong></label><br />
				<label for="<?php echo $this->get_field_id( 'image-'.$blog['blog_id'] ); ?>"><?php _e( 'Image Url:' ); ?></label> 
				<input class="widefat" id="<?php echo $this->get_field_id( 'image-'.$blog['blog_id'] ); ?>" name="<?php echo $this->get_field_name( 'image-'.$blog['blog_id']); ?>" type="text" value="<?php echo esc_attr( $image ); ?>" />
			</p>
			<?php
		}
	}

Step 4 Writing the Update Function

The Update Function will save the values entered in our widget form. First we make the variable $instance an array, then we make another loop of each blog. During the loop we will update the old $instance with $new_instance then we return the variable.

	public function update( $new_instance, $old_instance ) {
		// processes widget options to be saved
		$instance = array();
		foreach ($this->blogs AS $blog) {
			$instance['image-'.$blog['blog_id']] = strip_tags( $new_instance['image-'.$blog['blog_id']]);
		}
		return $instance;
	}

Step 5 Writing the Widget Function

Finally, we have our widget function which will render HTML in our widget position. Within this function we add a foreach loop of our registered blogs and during each loop, we will define the image, link and name of the blog. We add an if statement to check to see if an Image Url was added in the widget panel, if no images were selected then the respectful blog will not be shown. This is one way that admin can choose to hide a blog from their widget list. Next we add some HTML, with an image of each blog wrapped in its blog path and at the bottom we call the blog's name. We finish the function by closing all open tags.

	public function widget( $args, $instance ) {
		// outputs the content of the widget
		foreach ($this->blogs AS $blog) {
			$image = $instance['image-'.$blog['blog_id']];
			$link = $blog['path'];
			$name = get_blog_details($blog['blog_id'])->blogname;
			if ($image) {
			?>
				<div>
					<div>
						<a href="<?php echo $link; ?>"><img src="<?php echo $image; ?>" width="125" border="0" alt="<?php echo $name; ?>" /></a>
					</div>
					<div><h3><?php echo $name; ?></h3></div>
				</div>
			<?php 
			}
		}
	}

Finished Code

<?php
/**
 * @package MyNetwork
 * @version 1.0.0
 */
/*
Plugin Name: Your Plugin Name Here
Plugin URI: http://yourpluginsite.com
Description: This displays your Blogs in your WP Network
Author: The Author Name Here
Version: 1.0.0
Author URI: http://theauthoraddress.com
*/
?>
<?php
class MyNetwork_Widget extends WP_Widget {
	public $blogs = null;

	public function __construct() {
		$this->blogs = get_blog_list( 0, 'all' );
		parent::__construct(
			'mynetwork_widget', // Base ID
			'MyNetwork_Widget', // Name
			array(
				'description' => __( 'Display List of Blogs in Site Network', 'text_domain' )
			) // Args
		);
	}

	public function form( $instance ) {
		// outputs the options form on admin
		foreach ($this->blogs AS $blog) {
			$image =  $instance['image-'.$blog['blog_id']];
			?>
			<p>
				<label><strong><?php echo get_blog_details($blog['blog_id'])->blogname; ?></strong></label><br />
				<label for="<?php echo $this->get_field_id( 'image-'.$blog['blog_id'] ); ?>"><?php _e( 'Image Url:' ); ?></label>
				<input class="widefat" id="<?php echo $this->get_field_id( 'image-'.$blog['blog_id'] ); ?>" name="<?php echo $this->get_field_name( 'image-'.$blog['blog_id']); ?>" type="text" value="<?php echo esc_attr( $image ); ?>" />
			</p>
			<?php
		}
	}

	public function update( $new_instance, $old_instance ) {
		// processes widget options to be saved
		$instance = array();
		foreach ($this->blogs AS $blog) {
			$instance['image-'.$blog['blog_id']] = strip_tags( $new_instance['image-'.$blog['blog_id']]);
		}
		return $instance;
	}

	public function widget( $args, $instance ) {
		// outputs the content of the widget
		foreach ($this->blogs AS $blog) {
			$image = $instance['image-'.$blog['blog_id']];
			$link = $blog['path'];
			$name = get_blog_details($blog['blog_id'])->blogname;
			if ($image) {
				?>
				<div>
					<div>
						<a href="<?php echo $link; ?>"><img src="<?php echo $image; ?>" width="125" border="0" alt="<?php echo $name; ?>" /></a>
					</div>
					<div><h3><?php echo $name; ?></h3></div>
				</div>
				<?php 
			}
		}
	}
}
add_action( 'widgets_init', create_function( '', 'register_widget( "mynetwork_widget" );' ) );
?>

Conclusion

The styling of the blog was not covered in this tutorial but one can style the divs into a horizontal display or add some jQuery effects to make them scroll, fade or jump. I hope you find this tutorial useful and you adapt some of the snippets into your own widget. A great idea would be a carousel of registered site blogs. Please leave your feedback below. Happy coding!

Related Posts
  • Code
    Theme Development
    Custom Controls in the Theme CustomizerTheme customizer custom control 400
    In the last article, we explored the advanced controls available in the Theme Customizer, and how to implement them. We’re going to look at how to create our own custom control, allowing you to choose which Category of Posts are displayed on the home page. To get started, download version 0.6.0 of our Theme Customizer Example.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme From Static HTML: The Footer FileCreating wordpress theme from html 400
    In this series, you've been learning how to create a WordPress theme form static HTML. Up to this point, you have: prepared your markup for WordPress converted your HTML to PHP and split your file into template files edited the stylesheet and uploaded your theme to WordPress added a loop to your index file added meta tags, the wp_head hook and the site title and description to your header file added a navigation menu added widget areas to the header and sidebar. Read More…
  • Code
    Creative Coding
    A Look at the WordPress HTTP API: A Practical Example of wp_remote_postDiagram http api
    In the previous article, we reviewed the previous articles regarding GET requests, the native PHP facilities for making requests, and reviewed WordPress wp_remote_post API function along with the arguments that it offers. In this article, we're going to make use of wp_remote_post such that we're actually able to see it in action. Remember that this - like wp_remote_post - is part of the HTTP API of which there are other functions worth reviewing. But, for now, we're going to put wp_remote_post to work. Specifically, we're going to do the following: When the page loads, we're going to submit some information to a custom script The script will examine the information and return it to our page We'll then display the data on the page Sure, it's a bit of a contrived example but it will give us the experience of creating a separate PHP script that can be used for operations triggered by the use of wp_remote_post. Anyway, for the purposes of this example, we are going to use the PHP $_SERVER collection to log when the user has submitted their preference rather than require that they have logged in. Finally, the source code will be made available on GitHub and accessible at the end of this series in the following article. For now however, let's get started with working on the plugin.Read More…
  • Code
    Plugins
    A Better Forum List Widget for bbPressBbpress
    When bbPress was still a standalone installation, I had tried it out and wasn't really impressed. Things were clunky and it didn't always work the way it was supposed to. After languishing for a few years, Automattic decided to take bbpress and turn it into a plugin, improving the functionality leaps and bounds and making it a strong contender amongst other forum option for WordPress.Read More…
  • Code
    Widgets
    Building a Countdown Timer WidgetBuilding a countdown timer widget preview
    We all love a celebration, and now that Easter is over, we look forward to the next occasion. How far away is the next occasion you like to celebrate? Whatever it might be, let's build a widget plugin to add a countdown timer to our sidebar showing how long we have left to wait.Read More…
  • Code
    Business
    Making the Best of Google AdSense in WordPressGoogleadsensepreview
    Blog monetization is not a "must", but it's a very important source of motivation. Whether you're blogging alone or along with some authors you gathered, earning even a few bucks a month can change your and/or your authors' approach to your blog. Since Google AdSense is one of the easiest and most popular ways for blog monetization, we're going to see how to use it with a WordPress blog with multiple authors. (Although, this tutorial will also work for single bloggers.) We'll be covering how to set up profile fields for authors' AdSense ads and how to display those ads with a function, with a widget, with a shortcode and automatically inside posts.Read More…