Wordpress & Web Development

How To Create Your Own Basic WordPress Widgets

James Bruce 20-05-2011

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 2 New Cool Wordpress Plugins & Understanding The Wordpress Theme Structure This week I'll be a taking a look at a superior alternative to the often praised All-In-One SEO; a plugin that gives you the power of a Wordpress publishing system but allows you to output... Read More .

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 Set Up Your Blog With WordPress: The Ultimate Guide Want to start your own blog but don't know how? Look to WordPress, the most powerful blogging platform available today. Read More , 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.

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>
  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;;
    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:

if (have_posts()) : 
	while (have_posts()) : the_post(); 

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:

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:


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:

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


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.

Related topics: Blogging, Programming, Wordpress.

Affiliate Disclosure: By buying the products we recommend, you help keep the site alive. Read more.

Whatsapp Pinterest

Leave a Reply

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

  1. Debraj
    December 17, 2017 at 4:02 pm

    Hi, Can I add a Custom HTML widget (where I can put HTML codes) into this widget code?

  2. Anonymous
    July 6, 2015 at 3:43 am

    Hi James! First of all, thanks for the code. With your help I could create a custom widget with popular posts based on views. It worked like a charm in my site but now I discovered that the content of the widget is not showing on the sidebar of my search results (search.php). In index, category results, pages and custom page templates the widget is showing ok, but in search results shows only the widget title and no content. What could be happening? Any help or tip would be appreciated. Thanks again!!!! P.S: sorry if my English is not good

    • James Bruce
      July 6, 2015 at 9:41 am

      Hi Mario. There's nothing in the widget code that would prevent it showing on a search page, so I suspect your particular template either doesn't have the sidebar setup for search template, or has a special one defined. Do other widgets work on it? Unfortunately fixing that would require editing the search.php template found in your theme files, and probably some CSS modifications.

      • Anonymous
        July 6, 2015 at 11:39 am

        Hi James! Thanks for your reply. I'm using a custom template, made by myself from scratch, so maybe you're right but the strange thing is that other widgets are working normally on search results page (example wp-polls widget). I'm using the function on all the php's of my template... Should I use a different function to call the sidebar in search results?

        Sometimes it seems that WordPress works in misterious ways to me hehe... Thanks again!

        • Anonymous
          July 6, 2015 at 11:41 am

          Sorry, I forgot to delete the php line... the function I mean is: get_sidebar();

        • James Bruce
          July 6, 2015 at 11:47 am

          That's odd that it works with other widgets. Does the widget title appear, without content? Or does the widget just not appear at all?

          If it's the content thats not appearing, might be some special wp_Query thing, try replacing the query_posts with a new wp_query object, like the code here: https://codex.wordpress.org/Class_Reference/WP_Query

          If it's not appearing at all, I don't have any ideas I'm afraid.

        • asdf
          November 26, 2015 at 12:59 pm


      • Developer
        August 20, 2016 at 10:04 am

        Thank You james you are superb !

  3. Anonymous
    June 17, 2015 at 7:18 am

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

  4. Adrian
    April 9, 2015 at 4:00 pm

    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!

  5. Susan
    April 7, 2015 at 9:46 pm

    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.

  6. Riccardo
    March 30, 2015 at 12:54 pm

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

  7. Abi
    January 4, 2015 at 6:17 pm

    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
      January 4, 2015 at 9:07 pm

      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.

  8. Hamlet D'Arcy
    June 9, 2011 at 8:28 am

    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
      June 9, 2011 at 8:44 am

      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
      June 11, 2011 at 6:23 am

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

  9. Sietse
    June 2, 2011 at 7:59 am

    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" ( [Broken URL Removed] )


    • James Bruce
      June 9, 2011 at 8:44 am

      Very nice! Glad I could help!

  10. Chamomor
    May 25, 2011 at 9:04 pm

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

    • James Bruce
      May 25, 2011 at 9:57 pm

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

  11. Tim - TekFreak.com
    May 21, 2011 at 10:44 am

     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!

  12. realcostdomains
    May 21, 2011 at 2:08 am

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