How To Create Your Own Basic WordPress Widgets

Ads by Google

how to create 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.

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.

Ads by Google

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!“.

how to create 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.

write your own widget

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:

write your own widget

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();

write your own widget

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.

how to create 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
Comments (15)
  • Shiv B

    Really Helpful Tut…..
    Thank you. Now i have got basic idea how to start building widget.

  • Adrian

    Brilliant post, I have a basis to start now. Thanks also for all the comments about activating it, I forgot this until I read the comments!

  • Susan

    Thank you very much for this widget tutorial. I need to make a few for my theme and now I can go about doing them.

  • Riccardo

    Thank you. Thanks to this article I just created my first widget: custom category search.

  • Abi

    Shouldnt this use wp_query??
    “This function isn’t meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use of pre_get_posts hook, for this purpose. “

    • James Bruce

      No, query_posts() is the correct way to call a new loop. We’re not modifying the main page query; we’re making a new one on the sidebar.

Load 10 more
Affiliate Disclamer

This review may contain affiliate links, which pays us a small compensation if you do decide to make a purchase based on our recommendation. Our judgement is in no way biased, and our recommendations are always based on the merits of the items.

For more details, please read our disclosure.
Affiliate Disclamer

This review may contain affiliate links, which pays us a small compensation if you do decide to make a purchase based on our recommendation. Our judgement is in no way biased, and our recommendations are always based on the merits of the items.

For more details, please read our disclosure.