Random Article in a Widget

Share on Google+0Share on Facebook0Tweet about this on TwitterEmail this to someone

The last time it was a shortcode. Now it’s a widget. It will display the first few words of a randomly selected post along with its title and a link to the article itself. Here’s the code, and we’ll discuss it afterwards:

<?php
/**
 * Plugin Name: Random Article Widget
 * Description: Displays a random article's excerpt in a widget
 * Version: 0.1.0
 * Author: geomagas
 *
 */
 
add_action('widgets_init',function(){register_widget('RandomArticle_Widget');});

class RandomArticle_Widget extends WP_Widget
    {
	
	function __construct()
		{
		parent::__construct(
			'random-article-widget',
			'Random Article Widget',
			array('description',"A widget that displays a random article's excerpt")
			);
		}
		
	function widget($args,$instance)
		{
		$posts=get_posts();
		if($n=count($posts))
			{
			$post=$posts[rand(0,$n-1)];
			echo $args['before_widget'];
			echo $args['before_title'].$post->post_title.$args['after_title'];
			$xrpt=wp_trim_words(do_shortcode($post->post_content));
			$url=get_permalink($post->ID);
			echo "<p>$xrpt <a href='$url'>Read More &raquo;</a></p>";
			echo $args['after_widget'];
			}
		}
		
	}
    

Constructing a widget is a two-step procedure: defining it and registering it. To register our widget, we’ll have to call register_widget() giving its class name as a parameter. And this must be done during the widgets_init action.

Now, to define it we need to extend the WP_Widget class. At bare minimum, we will need to implement two of its methods: the constructor and widget().

Our constructor will simply call the inherited WP_Widget constructor with three parameters:

  • the new widget’s id
  • its title, as we want it to appear in the admin interface, and
  • an array with some other parameters. I chose to pass its description only, as it will appear in the admin interface.

widget() is the method responsible for rendering our widget. Its first parameter contains some theme-specific arguments, while the second refers to the specific instance (remember, multiple widgets of the same type can be shown on the same page).

After we get all posts using get_posts(), and provided that there is at least one, we pick a random one. Then, we render the title, the first few words (using wp_trim_words()) as well as a link pointing at the article itself.

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
Share on Google+0Share on Facebook0Tweet about this on TwitterEmail this to someone

1 comment on “Random Article in a Widget

  1. Pingback: Random Post Trivia | geomagas.gr

Submit comment

Allowed HTML tags: <a href="http://google.com">google</a> <strong>bold</strong> <em>emphasized</em> <code>code</code> <blockquote>
quote
</blockquote>