Random Post Trivia

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

Well, the Random Article Widget inspired me somehow…

Let’s say that we wanted a “Did you know that…” teaser to appear in the widget instead of an excerpt. Let’s say, for example, that we had an article about the grey whale. Our widget could show a trivia phrase such as:

Did you know that the average adult grey whale weights about 26 tons?

…followed by a “Read More ” link to the actual article.

To accomplish that, we will need to selectively associate our content with trivial phrases. We will use a metabox for the purpose:

 * Plugin Name: Post Trivia
 * Description: Associates a post with a trivia phrase
 * Version: 0.1.0
 * Author: geomagas
// meta box

function post_trivia_admin_init()

function post_trivia_add_meta_boxes()
	add_meta_box('post_trivia',"Did You Know That...",'post_trivia_meta_box','post','side','high');
function post_trivia_meta_box($post)
	<textarea name='post_trivia' id='post_trivia'><?php echo get_post_meta($post->ID,'_post_trivia',true); ?></textarea>
function post_trivia_save_post($post_id,$post)

Notice that, if the post trivia is empty, we delete the meta field instead of setting it to an empty value, so that the widget’s post query is able to only select posts that have the corresponding meta field set:

// widget


class PostTrivia_Widget extends WP_Widget
	function __construct()
			'Post Trivia Widget',
			array('description',"A widget that displays a random article's trivia")
	function widget($args,$instance)
			echo $args['before_widget'];
			echo $args['before_title'].'Did you know that...'.$args['after_title'];
			echo "<blockquote><strong><em>...$xrpt</em></strong></blockquote><p style='text-align:right;'><a href='$url'>Read More &raquo;</a></p>";
			echo $args['after_widget'];

The widget is implemented pretty much the same way as the Random Article’s one. The only differences are that (1) we filter the query by the existence of a _post_trivia meta field and (2) we output the trivia instead of the excerpt.

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

Submit comment

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