Many 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.
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!“.
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.
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:
<h1>This is my new widget!</h1>
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:
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 "<ul>";
while (have_posts()) : the_post();
echo "<li><a href='".get_permalink()."'>".get_the_title()."</a></li>";
endwhile;
echo "</ul>";
endif;
wp_reset_query();
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 "<ul>";
while (have_posts()) : the_post();
echo "<li><a href='".get_permalink()."'>".get_the_title();
echo the_post_thumbnail(array(220,200));
echo "</a></li>";
endwhile;
echo "</ul>";
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.
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.
Read comments: Loved it? Hated it? Join discussion here ...
More articles about: blogging, blogging tips, coding, DIY, How-To Articles, widgets, wordpress
Similar articles:
- How To Jazz Up Your WordPress Blog By Adding Featured Images (5 comments ...)
- The 5 Free WordPress Templates To Dress Up Your Blog (26 comments ...)
- Save $87 By Making A Free ‘Thesis’ WordPress Theme Clone (25 comments ...)
- People Love You? Show It Off On WordPress With Collision Testimonials (3 comments ...)
- Make Your WordPress Blog iPad Friendly with Onswipe (4 comments ...)
No comments:
Post a Comment
[Please do not advertise, or post irrelevant links. Thank you for your cooperation.]