Random Sentences, your first WordPress plugin

I have been reading about WordPress plugin development, and I have written a dummy example. This plugin allows you to include random sentences in your blog. This is used in a lot of sites, for example, to change a phrase that appears under the main title. I felt very creative, so I called this plugin “Random Sentences” (hurray for me!).

First, we have to create a random-sentences.php file in our wp-content/plugins folder, and write the plugin info in it.

<?php
/*
Plugin Name: Random Sentences
Version: 0.1
Plugin URI: http://www.albertobustamante.com
Description: Basic plugin that shows a random sentence
Author: Alberto Bustamante
Author URI: http://www.albertobustamante.com
*/

?>

If you check your plugins in your WordPress installation, you will see our great brand new plugin with the information you wrote in the file:

But right now, our plugin is kind of boring, isn’t? Lets write the function that will choose a random sentence. I have called it get_random_sentence():

<?php
/*
Plugin Name: Random Sentences
Version: 0.1
Plugin URI: http://www.albertobustamante.com
Description: Basic plugin that shows a random sentence
Author: Alberto Bustamante
Author URI: http://www.albertobustamante.com
*/

function get_random_sentence(){

	$all_sentences = array(
		1 => array( "sentence" => "This is the sentence 1",
					"author" => "Anonymous 1" ),
		2 => array( "sentence" => "This is the sentence 2",
					"author" => "Anonymous 2" ),
		3 => array( "sentence" => "This is the sentence 3",
					"author" => "Anonymous 3" ),
	);

	$min = 1;
	$max = 3;
	$index = rand($min,$max);

	$output =
		'<div id="RS_div">
			<p id="RS_sentence">'
				.$all_sentences[$index]["sentence"].
			'</p>
			<p id="RS_author">'
				.$all_sentences[$index]["author"].
			'</p>
		</div>';

	echo $output;
}

?>

As you can see, its a very simple function. It uses an array to store the sentences and its authors. I will try to store the sentences in the data base in the next version.
If you want to use this code, save the file, activate the plugin and include this line where you want the random sentences to appear:

<?php get_random_sentence(); />

Finally, write your own CSS code to adapt the output to your theme (I included ids in the html tags to do it).

Powered by WordPress with GimpStyle Theme design by Horacio Bella.
Entries and comments feeds. Valid XHTML and CSS.