Create a Wordpress Recent-Posts Widget

May 17, 2007 | Published in: Wordpress & plugins | Tags: , , , , , , 38

Wordpress WidgetsWidgets are a cool new feature built into wordpress version 2.2, and allow you to drag mini plugins into your widget-enabled theme’s sidebars.

They have all kinds of uses, searches, polls, you name it.

This article will show you how to create a customisable Recent post widget for yourself.


Step 1 – Creating the file

First create a file called myRecentPosts_widget.php, you can call it what you like really, as long as you know what it is. Open it up in your favorite text/code editor.

Lets start by adding the ‘php’ tag and some information about the author:

1
2
3
4
5
6
7
8
<?php
/*
Plugin Name: My Recent Posts widget
Description: Adds a sidebar widget to display posts from a specified category
Author: Mike Jolley, jolley_small@tesco.net
Version: 1.0
Author URI: http://blue-anvil.com
*/

Done that? Well done, lets move on.

Step 2 – The widget function begin

Next we need to add the widgets functionality. Lets add the start of our function: the init function, which will wrap all our plugin functionality. We will also add a little code to make sure widgets are enabled (and the widget functions exist), to avoid errors:

1
2
3
4
function widget_myRecentPosts_init() {
 
	if ( !function_exists('register_sidebar_widget') )
		return;

Now we can start adding our widgets functionality, the next code creates our function and gets variable values (some of these we will set later).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function widget_myRecentPosts($args) {
 
		// "$args is an array of strings that help widgets to conform to
		// the active theme: before_widget, before_title, after_widget,
		// and after_title are the array keys." - These are set up by the theme
		extract($args);
 
		// These are our own options
		$options = get_option('widget_myRecentPosts');
		$title = $options['title'];  // Title in sidebar for widget
		$show = $options['show'];  // # of Posts we are showing
		$excerpt = $options['ex'];  // Showing the excerpt or not
		$exclude = $options['exclude'];  // Categories to exclude
                      if ($show<1) $show = 1;
		if ($exclude=="") $exclude = "0";

The next piece of code will start outputting to the screen, using the default $args, and our widget title.

1
2
                      // Output
		echo $before_widget . $before_title . $title . $after_title;

Step 3 – The Posts Query

The next code starts pulling results from the database using queries. This is more complex, so don’t worry if it confuses you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// GET POSTS
			global $wpdb;
			$sql = 'select DISTINCT * from '.$wpdb->posts.'
			INNER JOIN (select * from '.$wpdb->post2cat.'
			INNER JOIN '.$wpdb->categories .' ON '.$wpdb->post2cat.'.category_id = '.$wpdb->categories .'.cat_ID)
			as A ON '.$wpdb->posts.'.ID = A.post_ID
			WHERE (A.cat_ID NOT IN ('.$exclude.'))
			AND '.$wpdb->posts.'.post_status="publish"
			AND '.$wpdb->posts.'.post_type="post"
                        GROUP BY ID
			ORDER BY '.$wpdb->posts.'.post_date
			DESC LIMIT 0,'.$show.';';
 
			$posts = $wpdb->get_results($sql);

The above query gets all posts that are published, not excluded (from one of our options), and orders them by date, limiting the number queried to another of our options.

The next piece of code checks if we had any results, and starts looping to output them in the sidebar.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
			// start list
			echo '<ul>';
				// were there any posts found?
				if (!empty($posts)) {
					// posts were found, loop through them
					 foreach ($posts as $post) {
 
							// format a date for the posts
							$post->post_date = date("F j, Y",strtotime($post->post_date));
 
							// if we want to display an excerpt, get it/generate it if no excerpt found
							if ($ex) {
								 if (empty($post->post_excerpt)) {
									 $post->post_excerpt = explode(" ",strrev(substr(strip_tags($post->post_content), 0, 100)),2);
									 $post->post_excerpt = strrev($post->post_excerpt[1]);
									 $post->post_excerpt.= " [...]";
								 }
							}
 
							//output to screen
							echo '<li>
							<a class="post" rel="bookmark" href="'.get_permalink($post->ID).'"><span class="inner">
							<strong class="title lifestyle">'.$post->post_date.' - '.$post->post_title.'</strong>';
 
							if ($ex) echo '<br />'.strip_tags($post->post_excerpt);
 
							echo '</span></a></li>';
					 }
				} else echo "<li>No recent Posts</li>";
		// end list
		echo '</ul>';

That was a lot, but its commented so read through to get a better understanding of how the rows are outputted. To finish our function we just close the function (and output the closing element of the widget).

1
2
3
// echo widget closing tag
		echo $after_widget;
	}

Step 4 – Creating the settings

Widgets make it easy to create a small settings dialog for your widget, our widget is going to get settings for:

  • Widget title
  • posts to show
  • whether or not to show excerpt
  • Categories to exclude from the list

Lets get started. We declare our settings function, and load the variables.

1
2
3
4
5
6
7
8
	// Settings form
	function widget_myRecentPosts_control() {
 
		// Get options
		$options = get_option('widget_myRecentPosts');
		// options exist? if not set defaults
		if ( !is_array($options) )
			$options = array('title'=>'Recent Posts', 'show'=>'5', 'excerpt'=>'1','exclude'=>'');

Next we check if the settings form has been posted, updating the settings if it has.

1
2
3
4
5
6
7
8
9
10
                      // form posted?
		if ( $_POST['recentArticles-submit'] ) {
 
			// Remember to sanitize and format use input appropriately.
			$options['title'] = strip_tags(stripslashes($_POST['recentArticles-title']));
			$options['show'] = strip_tags(stripslashes($_POST['recentArticles-show']));
			$options['excerpt'] = strip_tags(stripslashes($_POST['recentArticles-excerpt']));
			$options['exclude'] = strip_tags(stripslashes($_POST['recentArticles-exclude']));
			update_option('widget_myRecentPosts', $options);
		}

So we have handled posted options, now we need a form! Lets get the options to show in the form by default.

1
2
3
4
5
		// Get options for form fields to show
		$title = htmlspecialchars($options['title'], ENT_QUOTES);
		$show = htmlspecialchars($options['show'], ENT_QUOTES);
		$excerpt = htmlspecialchars($options['excerpt'], ENT_QUOTES);
		$exclude = htmlspecialchars($options['exclude'], ENT_QUOTES);

Now we can happily display the form. Notice we only need to write the fields, the widgets engine handles the form code!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
		// The form fields
		echo '<p style="text-align:right;">
				<label for="myRecentPosts-title">' . __('Title:') . '
				<input style="width: 200px;" id="myRecentPosts-title" name="myRecentPosts-title" type="text" value="'.$title.'" />
				</label></p>';
		echo '<p style="text-align:right;">
				<label for="myRecentPosts-show">' . __('Show:') . '
				<input style="width: 200px;" id="myRecentPosts-show" name="myRecentPosts-show" type="text" value="'.$show.'" />
				</label></p>';
		echo '<p style="text-align:right;">
				<label for="myRecentPosts-excerpt">' . __('Show excerpt:') . '
				<input style="width: 200px;" id="myRecentPosts-excerpt" name="myRecentPosts-excerpt" type="text" value="'.$excerpt.'" />
				</label></p>';
		echo '<p>Enter the categories to exclude below, this must be a comma separated list of category id\'s!</p>';
		echo '<p style="text-align:right;">
				<label for="myRecentPosts-exclude">' . __('Exclude:') . '
				<input style="width: 200px;" id="myRecentPosts-exclude" name="myRecentPosts-exclude" type="text" value="'.$exclude.'" />
				</label></p>';
		echo '<input type="hidden" id="myRecentPosts-submit" name="myRecentPosts-submit" value="1" />';
	}

And thats that for settings!

Step 5 – Register the widgets

The last piece of code registers the widget for use. After that were done.

1
2
3
4
5
6
7
8
9
10
11
	// Register widget for use
	register_sidebar_widget(array('My Recent Posts', 'widgets'), 'widget_myRecentPosts');
 
	// Register settings for use, 300x100 pixel form
	register_widget_control(array('My Recent Posts', 'widgets'), 'widget_myRecentPosts_control', 300, 200);
}
 
// Run code and init
add_action('widgets_init', 'widget_myRecentPosts_init');
 
?>

Widget armed

Now its finished, upload to plugins directory, activate it, then go to the widgets control panel (under the presentation tab of the wordpress admin) and drag it into one of your sidebar widget sections.

Added widget

Click the little form icon on the widget to bring up the settings form

Settings

In action it looks like this:

In action

Lazy mans corner

For a full code listing, click here

Download it all zipped up below.

Download My Recent posts widget Version 1.1


Enjoy

I hope my little tutorial on widget creation was of a great help :)

Found this post useful? Why not buy me a coffee!

Related Entries

Popular Entries

38 Responses to “Create a Wordpress Recent-Posts Widget”

RSS feed for comments on this post.

Pages: « 1 2 3 [4] Show All

  • 29 - test says: Reply to this comment

    Gravatar

    test

    Comment made on February 11, 2009 at 10:23 am

  • 30 - James says: Reply to this comment

    Gravatar

    Great widget.

    Is there any way I can add a recent posts widget to display recent posts on my static home page?

    Any help please email me

    Thanks

    Comment made on February 16, 2009 at 5:38 pm

  • 31 - regalos originales says: Reply to this comment

    Gravatar

    You now what? some people would say fire is cold…

    Comment made on March 3, 2009 at 11:35 pm

  • 32 - regalos originales says: Reply to this comment

    Gravatar

    Where should I paste the code?

    Comment made on March 3, 2009 at 11:53 pm

  • 33 - tashweb says: Reply to this comment

    Gravatar

    you need to add functionality

    Comment made on March 3, 2009 at 11:58 pm

  • 34 - KFGD63 says: Reply to this comment

    Gravatar

    Hey Man,

    Thanks for your useful tutorial regarding registration widget.

    Regarding the (Zip File) download, after downloading where i will put it?

    Thanks in advance for your reply.

    Ciao

    KFGD63

    Comment made on March 19, 2009 at 1:16 pm

  • 35 - Faisal Khan says: Reply to this comment

    Gravatar

    For me this didn’t work.

    I used therefore this code instead of your snippet where you assess the database. It uses function and do not assess the database.
    // GET POSTS
    $r = new WP_Query(array('showposts' =&gt; $show, 'what_to_show' =&gt; 'posts', 'nopaging' =&gt; 0, 'post_status' =&gt; 'publish', 'caller_get_posts' =&gt; 1));
    if ($r-&gt;have_posts()) :
    ?&gt;

    have_posts()) : $r-&gt;the_post(); ?&gt;
    &lt;a href=""&gt; </a>

    &lt;?php
    // echo widget closing tag
    echo $after_widget;

    wp_reset_query(); // Restore global post data stomped by the_post().
    endif;

    Comment made on March 26, 2009 at 1:32 am

  • 36 - Exam Philippines says: Reply to this comment

    Gravatar

    thank for you for sharing this tutorial on how to create recent post. god bless!!!

    Comment made on March 28, 2009 at 5:48 pm

  • 37 - Administrare Damien says: Reply to this comment

    Gravatar

    Excelent job, thanks!

    Comment made on May 15, 2009 at 9:39 pm

  • 38 - Obrazy says: Reply to this comment

    Gravatar

    great tutorial, thanks!

    Comment made on May 28, 2009 at 7:57 pm

Pages: « 1 2 3 [4] Show All

About this site

Blue Anvil is the online web design journal & portfolio of , a web designer from Norfolk, England. Read More »
ThemeSlice
  • Featured work - More

    • Beefjack
    • Integrity
    • theotaku.com
    • Manic Melon
  • Latest Tweet - More

    • Dropped yoghurt all down my pyjamas. Bugger. Working in my boxers. Ill get dressed some time. Soon.
  • Out of the blue - More

    • Wordpress 2.8 Memory Usage

      With the release of wordpress 2.8 some people are experiencing out of memory php errors along the lines of:

      Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 228968 bytes)

      You may also be seeing pages fail to load fully (for example the wordpress admin dashboard) if php error messages are hidden. I’ve already had one case where we thought certain plugins were to blame but in fact it was just out of memory. A possible fix (which worked in the previously mentioned case) is to add:

      @ini_set('memory_limit','64M');

      to your wp-config file. Has anyone else encoutered this error?

    • jQuery Curvy Corners 1.x and 2.x updated and moved to Google Code

      I have updated the jQuery Curvy Corners plugins (both versions) with jQuery 1.3.2 support and other enhancements. The beta 2 version is looking good and is working in all version of IE, Opera, and Firefox (as far as I can tell).

      You can grab the latest files from Google Code here. Enjoy.

    • I’m too nice: Wordpress Download Monitor plugin page add-on now included with Download Monitor version 3.1.

      It was going to be a paid add-on, but today I had a change of heart and bundled it with the newest version of download monitor. The add-on lets you make a download page using a shortcode; it lists your downloads/categories with full sorting, pagination, and search functionality. Not bad eh? See the documentation topic to see full instructions for usage, or see my download page to see it in action.

      And if you use it, please consider making a donation to ensure the continued development of the plugin!

    • 2 Announcements: New Support forum, and feedback wanted for new download page add-on

      First, I’ve implemented a support forum to Blue Anvil mainly for plugin support and ideas which can be found here. Hopefully this will make supporting my plugins easier. Feel free to add to the discussions (there is also a general web design forum too).

      Secondly, I’ve added a demo of the new download page add-on I’m making for Download Monitor. This will be a paid add-on and it would be cool to get any feedback or suggestions from anyone who would like such a feature. My download page is here. Please leave feedback on the forum or in the comments.