All PostsTutorialsWordPress

In today’s WordPress tutorial, I will show you how to create a WordPress widget that you can use to display a number of your recent blog posts. Creating and using a recent posts widget like this will allow you to remove unnecessary WordPress plugins and give you greater flexibility in where you can output you recent posts. This tutorial will provide a step by step breakdown of how I created this WordPress recent posts widget.

Create Your Widget

First I create a new PHP file in my functions folder, if you do not have a functions folder create it in your theme folder. This new PHP file will be called “widget-recent-posts.php”.

Configure Your Widget

In your new PHP widget file named widget-recent-posts.php open it up and add the below code:

/*-----------------------------------------------------------------------------------
	Plugin Name: Recent Posts Widget
	Plugin URI: https://www.webadelic.co.uk
	Description: Displays recent blog posts from a standard post type.
	Version: 1.0
	Author: David Martin
	Author URI: https://www.webadelic.co.uk
-----------------------------------------------------------------------------------*/

// Add webadelic_recent_blog_widgets function to widgets_init, this will load the widget.
add_action( 'widgets_init', 'webadelic_recent_blog_widgets' );

// Register the widget.
function webadelic_recent_blog_widgets() {
	register_widget( 'Webadelic_Recent_Blog_Widget' );
}

// Extend WP_Widget with our widget.
class webadelic_recent_blog_widget extends WP_Widget {

/*-----------------------------------------------------------------------------------*/
/*	Widget Setup
/*-----------------------------------------------------------------------------------*/
	
	function Webadelic_Recent_Blog_Widget() {
	
		// Widget setup
		$widget_ops = array( 'classname' => 'webadelic_recent_blog_widget', 'description' => __('Tutorial to show how to display recent posts from a standard post type', 'framework') );

		// Widget UI
		$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'webadelic_recent_blog_widget' );

		// Widget name and description
		$this->WP_Widget( 'webadelic_recent_blog_widget', __('Webadelic - Recent Posts Widget', 'framework'), $widget_ops, $control_ops );
	}

}

In the above code we have added the function ‘webadelic_recent_blog_widgets’ to widget_init, we have also registered the widget with the name of the class (webadelic_recent_blog_widget) that we will use to extend WP_Widget. The class WP_Widget is all that is needed in order to create a widget, we just need to extend the class using the functions I will add below.

You will also see under the last code comment ‘Widget name and description’ this is how I have provided a named and a description for the widget. This information appears in your widget admin panel.

Include The Widget

Open up your functions.php file in your theme folder, here we will include the widget into our theme by using:

/*-----------------------------------------------------------------------------------*/
/*	Custom Recent Posts Widget
/*-----------------------------------------------------------------------------------*/

include('functions/widget-recent-posts.php');

In your ‘Widgets’ admin area in WordPress you will now see your new widget.

Display Your Widget Content

After the above function ‘Webadelic_Recent_Blog_Widget()’ has ended we can now begin to add the code that will display the widget contents to the front end user. The below function ‘function widget( $args, $instance )’ is used to output the contents of our widget to the user and grab some custom options that we can use later, for testing purposes I have added a simple text output ‘WIDGET TEST OUTPUT’. This is used to confirm our widget is working as expected, you will be able to see this output on your website where your widgets are pulled in, for example in the sidebar. Note: As of yet we have not added any options to the widget or pulled any data from WordPress, this will come later.

You will see below, that I have prepared a variable ‘$number’ to store our widget article count options which we will set up later, the $title variable grabs the title you enter into the widget options and $before_widget and $after_widget will output a div wrapper around the widget – this depends on your theme, but is often the case.

/*-----------------------------------------------------------------------------------*/
/*	Display The Widget To The Front End
/*-----------------------------------------------------------------------------------*/
	
	function widget( $args, $instance ) {
		extract( $args );
		
		//Widget title, entered in the widget settings
		$title = apply_filters('widget_title', $instance['title'] );

		/* Custom Options */
		
		// Our options from the widget settings.
		$number = $instance['number'];

		// Before widget - as defined in your specific theme.
		echo $before_widget;

		/* Display The Widget */
		
		// Output the widget title if the user entered one in the widget options.
		if ( $title )
			echo $before_title . $title . $after_title;
			
			//Test The Widget Is Working
			echo "WIDGET TEST OUTPUT"; 

		/* After widget - as defined in your specific theme. */
		echo $after_widget;
	}

The above code results with the below output to the user:

Check And Update The Widget Settings

The next function we need to add comes right after the above ‘function widget()’, this new function is called ‘function update()’. This is used to process the widget options and update the widget if new settings have been added, it simply overwrites the old data stored in the variable with new data.

/*-----------------------------------------------------------------------------------*/
/*	Update The Widget With New Options
/*-----------------------------------------------------------------------------------*/
	
	function update( $new_instance, $old_instance ) {
		
		$instance = $old_instance;
		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['number'] = strip_tags( $new_instance['number'] );

		return $instance;
	}

Create The Widget Options

Now for the fun part, our last function ‘function form()’ we will create the admin option fields for the widget, this will allow you to customize the widget title and the post output number.

In this function , first we are going to set some default settings for the widget, we use the array $defaults to store the default settings for each of our option fields. Notice, I close the PHP tags after
‘$instance = wp_parse_args( (array) $instance, $defaults )’, this is because I will need to output the admin option HTML to the widget admin area – remember to open the PHP tags again after the option HTML.

In the below function you will see I output two inputs to the widget admin area, these are to allow the WordPress admin user to amend the widget settings. In this widget I have provided the options to set the widget title and set how many articles to output.

/*-----------------------------------------------------------------------------------*/
/*	Widget Settings
/*-----------------------------------------------------------------------------------*/
	 
function form( $instance ) {

	/* Default Widget Settings */
		
	$defaults = array(
		'title' => 'Recent Posts',
		'number' => '4'
	);
		
	$instance = wp_parse_args( (array) $instance, $defaults ); 
		
?>

	
	<p>
		<label for="get_field_id( 'title' ); ?>">
		<input type="text" class="widefat" id="get_field_id( 'title' ); ?>" name="get_field_name( 'title' ); ?>" value="" />
	</p>
				
	
	<p>
		<label for="get_field_id( 'number' ); ?>">
		<input type="text" class="widefat" id="get_field_id( 'number' ); ?>" name="get_field_name( 'number' ); ?>" value="" />
	</p>
	

The Widget So Far

Currently we have have exteneded the class WP_Widget using the above functions, we have set the widget up, included it in the WordPress theme functions file so it now appears in the Widget admin area. We have also added three option inputs, we have given the widget to save these widget inputs and we have set defaults for the inputs.The result looks as follows:

WordPress Widget Admin Area

WordPress Theme Front End

Pulling WordPress Recent Articles

Now we have confirmed our widget is working and ouputs some test content as shown in the above screen shot, we can add the functionality to pull our latest blog posts.

In the post query bellow, I will use WP_Query, WP_Query is a class which is used to handle queries to your blog, it is great for creating secondary loops, you can do some pretty powerful stuff with it. Full WP_Query documentation is here.

In the code below we create a new query to begin our new post loop, we can pass our widget options to this query and this will allow us to output specific posts defined our options parameters. I am really only scratching the surfice of what options you can pass to the query, so read up on WP_Query and have a play!

You can see below, the paramters I am passing to the query are post_type – what blog content shall we grab (post/page), posts_per_page – which is used to set how many articles to show, ignore_sticky_posts – allows us to included or excluded sticky posts.

Now we have built our basic query, we can check if we have posts to show, if we do we use a while loop to grab the set amount of posts to be displayed. We loop through each post until we reach the set post output number defined in the widget options.

In this is example I simply output the post title and the post excerpt, however you can output a load of other data fromt the post should you wish.

<?php 

/* Create a new post query */
$query = new WP_Query();
//Send our widget options to the query
$query->query( array(
	'post_type' => 'post'
    'posts_per_page' => $number,
    'ignore_sticky_posts' => 1,
   )
 ));
 
<?php if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>
 
	<article>
		<h4><a href=""><?php the_title(); ?></a></h4>
		<p><?php the_excerpt(); ?></p>
	</article>
 					
<?php endwhile; endif; ?>
        
?>

The Resulting Post Query Output

The Resulting Widget Admin

References:

  • https://codex.wordpress.org/Class_Reference/WP_Query
  • https://codex.wordpress.org/Widgets_API