blog

Creating a WordPress Widget to Show a Random Post


Making a widget to show a random post uses two underlying concepts you need to get familiar with to be good at WordPress development: making use of WP_Query objects, and making widgets. If you’ve not checked them before, check out our Quick Guides which more thoroughly introduce both:

If you have, check out this video where I explain the pretty simple process I use to making a Random Post Widget:

; echo $args['before_title']; the_title(); echo $args['after_title']; echo get_the_excerpt(); echo $args['after_widget'];

  • We make sure that after the end of the loop we call wp_reset_postdata(). This undoes our “pollution” in $query->the_post() so that the rest of the site doesn’t act funky because of our widget. It’s just good hygiene.
  • Full Code for Making our Widget

    class QG_Widget extends WP_Widget {
    
    	/**
    	 * Sets up the widgets name etc
    	 */
    	public function __construct() {
    		$widget_ops = array( 
    			'classname' => 'qg_widget',
    			'description' => 'This is a widget for a quick guide',
    		);
    		parent::__construct( 'qg_widget', 'Quick Guide Widget', $widget_ops );
    	}
    
    	/**
    	 * Outputs the content of the widget
    	 *
    	 * @param array $args
    	 * @param array $instance
    	 */
    	public function widget( $args, $instance ) {
    		$q_args = array(
    			'orderby'        => 'rand',
    			'posts_per_page' => '1',
    
    		);
    		$query = new WP_Query( $q_args );
    		while ($query->have_posts()) {
    			$query->the_post();
    			echo $args['before_widget'];
    			echo $args['before_title'];
    			the_title();
    			echo $args['after_title'];
    			echo get_the_excerpt();
    			echo $args['after_widget'];
    		}
    		wp_reset_postdata();
    	}
    }
    
    add_action( 'widgets_init', function(){
    	register_widget( 'QG_Widget' );
    });

    Further Reading on Widgets and WP_Query

    The Complete Guide to Creating WordPress Widgets and Widget Areas

    Working with WP_Query

     

    Click to comment

    Leave a Reply

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

    Copyright © 2017 'Null Shop;.

    To Top