How To Create Your Own Basic WordPress Widgets

Ads by Google

widget sidebar featuredimage   How To Create Your Own Basic Wordpress WidgetsMany bloggers will search high and low for the perfect WordPress widget that will do exactly what they want, but with a little programming experience you may find it’s easier to write your custom widget.

This week I’d like to show how to do exactly that, and the widget we will be writing is a simple one that picks out a single random post from your site, pulls the featured image, and displays it on the sidebar – a visual “check this out” widget that will help users to find more content on your site.

This is also an extension of a continuing series in which I show you how easy it is to customize your WordPress template.

You may also be pleased to know that we’ve added a new WordPress Tutorials category to MakeUseOf, so be sure to check that out for an ever growing archive of up to date tips and guides to the world’s favourite blogging platform.

Key Concepts: WordPress Queries and the Loop

Each page on your blog consists of a query to your database of posts. Depending on the page you are viewing, the query will change. Your blog homepage for instance, may use the query “get the latest 10 blog posts“. When you view the category archives, the query may change to “get the latest 20 posts for the category family photos only, order the results by date published“. Each query will return a set of results, and depending on the page template being used, each result will be run through the main “loop” of the template.

Ads by Google

Each page can in fact consist of more than one query though, and you can even create your own queries to add functionality to various places in your template. You can see an example of this in use at the bottom of this article – we have a few additional queries that run on every page that aim to show you related articles you may be interested in, or articles which are trending this week.

To make our custom widget though, we will simply need to create an additional query that grabs X number of random posts plus their images, and displays them in some way on the sidebar. I already showed you last week the code to grab the featured image, so we really just need to know how to make a new WordPress widget and place it on the sidebar.

Basic Widget Code

Start by creating a new .php file in your wp-content/plugins directory. You could also follow the tutorial offline then upload it using the WordPress interface, but I find it’s easier to write as we go along in case you need to debug. Call your file whatever you like, but I’m going with random-post-widget.php

Paste the following into the file and save. Feel free to change the section at the top with my name in it, but don’t adjust the rest of the code yet. This is basically a skeleton empty widget, and you can see where it says //WIDGET CODE GOES HERE is where we will add our functionality in later.


<?php
/*
Plugin Name: Random Post Widget
Plugin URI: http://jamesbruce.me/
Description: Random Post Widget grabs a random post and the associated thumbnail to display on your sidebar
Author: James Bruce
Version: 1
Author URI: http://jamesbruce.me/
*/


class RandomPostWidget extends WP_Widget
{
  function RandomPostWidget()
  {
    $widget_ops = array('classname' => 'RandomPostWidget', 'description' => 'Displays a random post with thumbnail' );
    $this->WP_Widget('RandomPostWidget', 'Random Post and Thumbnail', $widget_ops);
  }
 
  function form($instance)
  {
    $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
    $title = $instance['title'];
?>
  <p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<?php
  }
 
  function update($new_instance, $old_instance)
  {
    $instance = $old_instance;
    $instance['title'] = $new_instance['title'];
    return $instance;
  }
 
  function widget($args, $instance)
  {
    extract($args, EXTR_SKIP);
 
    echo $before_widget;
    $title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
 
    if (!empty($title))
      echo $before_title . $title . $after_title;;
 
    // WIDGET CODE GOES HERE
    echo "<h1>This is my new widget!</h1>";
 
    echo $after_widget;
  }
 
}
add_action( 'widgets_init', create_function('', 'return register_widget("RandomPostWidget");') );?>

As it is, the plugin doesn’t do much apart from print out a large title with the words “This is my new widget!“.

new sidebar widget step1   How To Create Your Own Basic Wordpress Widgets

It does however give you the option to change the title, which is kind of essential for any widget. Adding in other options is a bit beyond the scope of this article today, so for now let’s move on to give it a real purpose.

sidebar options   How To Create Your Own Basic Wordpress Widgets

A New Query & The Loop

To make a new query to your blog database, you need to use the query_posts() function along with a few parameters, then run through the output using a while loop. Let’s try this – a very basic query and loop to demonstrate. Replace the line of code that says:

This is my new widget!

with the following:


// WIDGET CODE GOES HERE
query_posts('');	
if (have_posts()) : 
	while (have_posts()) : the_post(); 
		the_title();	
	endwhile;
endif; 
wp_reset_query();

This is an absolutely basic query using default options and zero formatting of the output. Depending on how your blog is set up, the default will most likely be to grab the 10 latest posts – then all the above code does is to output the title of each post. It’s pretty ugly, but it works:

new sidebar widget step2   How To Create Your Own Basic Wordpress Widgets

We can make it a little better right away just by adding some HTML formatting to the output with the ECHO command, and creating a link to the post using get_the_permalink() function:



query_posts('');
if (have_posts()) : 
	echo "
    "; while (have_posts()) : the_post(); echo "
  • ".get_the_title()."
  • "; endwhile; echo "
"; endif; wp_reset_query();

new sidebar widget step3   How To Create Your Own Basic Wordpress Widgets

Already, it’s looking much better. But we only want one post, picked at random. To do this, we specify some parameters in the query:



query_posts('posts_per_page=1&orderby=rand');

Of course, you could change it to any number of posts – in fact, there’s a whole range of extra bits you can pass into the query in order to restrict, expand, or change the order of the results, but let’s stick with that for now. If you refresh, you should see just one post which is randomized each time you refresh.

Now for the featured thumbnail. Replace the code with this, hopefully you can see where we are grabbing the thumbnail and displaying it:


query_posts('posts_per_page=1&orderby=rand');
if (have_posts()) : 
	echo "
    "; while (have_posts()) : the_post(); echo "
  • ".get_the_title(); echo the_post_thumbnail(array(220,200)); echo "
  • "; endwhile; echo "
"; endif; wp_reset_query();

You can see the finished results again on my development blog Self Sufficiency Guide, though I might have moved things around by the time you read this.

final complete widget   How To Create Your Own Basic Wordpress Widgets

Conclusion:

See how easy it is to make your own custom widget that can do exactly what you want? Even if you don’t understand 90% of the code I’ve shown you today, you should still be able to customise it somewhat by just changing variables or outputting different HTML. We wrote a whole widget today, but you could easily use just the new query and loop code on any of your page templates.

Problems? Need some different WordPress related help? I’m always on hand to help in MakeUseOf Answers, so head on over and post a new question there.

Ads by Google

10 Comments - Write a Comment

Reply

realcostdomains

 Great tips on this – there is money to be made for users who get creative with the idea.

Reply

Tim – TekFreak.com

 It’s amazing the time and effort people have put in to creating widgets for all to use for free.  This just may inspire to me to create my own.  Thanks!

Reply

Chamomor

Hello
What’s a pitty : too much publicity, can’t read your article.

James Bruce

What a pity – too much nonsense, punctuation errors and spelling mistakes, I can’t read your comment. What on earth are you talking about?

Reply

Sietse

w00t! This is SPOT ON for what I have in mind and it works like a charm. Couldn’t find it explained anywhere else on the web. Thank you so much!

You can see the result in my website’s sidebar, the widget is called “3 Random Lists” ( http://allyouneedislists.com/ )

Cheers!

James Bruce

Very nice! Glad I could help!

Reply

Hamlet D’Arcy

Alright, I struggled getting this to work for a while. 

After you create the .php file, your new widget will *not* show up in the Appearance->Widgets list until you activate it. Go to the plugins page and click activate on the widget, then it appears. 

James Bruce

Apologies, yes, although this isa widget, it is essentially still a wordpress plugin and all plugins must be activated before use. I should have mentioned that. 

Sietse

lol, it took me a while to realize that too :)

Reply

himanshu mishra

nice one

Your comment