DM Blog

DM Rating Stars — WordPress Plugin

by #blogging #code

For quite some time now, I’ve been using my own custom plugin on my WordPress blog to remove some annoying "features" of WordPress, add some new functionality, and automate a lot of tasks to make writing articles much quicker and easier. it’s more like several plugins bundled into one (including a couple of widgets as well), and it’s gone though numerous changes over the years. I originally blogged about it back in at the same time that I had re-designed by blog…

One of the features that my plugin adds to WordPress is the ability to add rating stars to articles. I use it a lot on my reviews of restaurants and food establishments, and now, I’ve decided to package it as a separate stand-alone plugin and make it available for download.

More importantly, however, I figured this plugin would be a good opportunity to share some PHP code (below) and help someone else out there who’s trying to get started with writing a WordPress plugin.

Download

If all you want is to download the plugin, here it is: DM Stars Plugin. All you have to do is copy the folder to your "plugins" folder and then activate it in your site’s admin area.

Instructions

To use it, you just have to use a shortcode: [stars rating="2.5" type="Service"] wherever you want the stars to appear. The plugin will display the correct amount of stars and do the rest for you. (The type="Service" part is optional and defaults to Overall Rating if you leave it out.) That might be a little hard to remember for some people, so the plugin also adds a new "Stars" button to the toolbar on your "edit posts" screen and prompts you to enter all the correct information. It couldn’t be any easier!

Here’s how it looks:

Service Rating: 2½ stars

PHP Code

And now, Here’s a more in-depth look at the code used in the plugin…

// [stars rating type] = Create Stars & optionally, a custom rating type (Otherwise, uses "Overall Rating")
function dm_stars_func($atts)
{
	extract(shortcode_atts(array(
		'rating'	=> 2.5,
		'type'		=> 'Overall'
	),$atts));

	// let’s generate our rating as a fraction
	$fraction  = floor($rating);										// first just the whole number part
	$fraction .= (($fraction – $rating) != 0) ? '½' : NULL;		// now append the "1/2" fraction if necessary

	// initialize some variables
	$stars		= $rating*10;
	$i			= 1;
	$images		= NULL;
	$path		= (is_feed()) ? plugins_url('',__FILE__) : str_ireplace(home_url(),'',plugins_url('',__FILE__));

	// loop through 5 times and create the images for our stars (concatenating them onto $images)
	while ($i <=5)
	{
		$value	 = ($stars > 10) ? 10 : $stars;
		$star	 = sprintf("%02d",$value);
		$images .= '<img src="'.$path.'/images/star'.$star.'.png" alt="star" border="0" width="32" height="32" style="float: none; margin: 0; padding: 0; border: none;" />';
		$stars	 = $stars – $value;
		$i++;
	}

	return '<div class="dm-stars2" style="float: none; margin: 1em auto; width: 160px;">'.
				$images.'<p style="background: #eee; margin: 0; padding: 0 0.5em; line-height: 1.5em; border-bottom: 1px solid #ccc; border-top: 1px solid #ccc; font-size: 0.75em; color: #444; text-align: center;">'.
				$type.' Rating: '.$fraction.' stars</p></div>';
}

This is the function that get’s called whenever WordPress encounters our [stars rating="2.5"] shortcode in one of our articles. We set the default rating to be 2.5 and our default rating type is Overall, but these values get overridden with whatever we specify in our shortcode. The next part converts our number (2.5) to a fraction (2½) and then determines the correct images to use for each of the five stars according to the rating number we’ve assigned. The function returns the HTML code that should be included in our article and effectively replaces our [stars rating="2.5"] shortcode.

// register the shortcode with WordPress
add_shortcode('stars','dm_stars_func');

// make sure the above short code is output on the RSS feeds too (and comments)
add_filter('the_excerpt_rss', 'do_shortcode');
add_filter('the_content_rss', 'do_shortcode');
add_filter('comment_text', 'do_shortcode',31); //since autop is run at level 30, we run this after auto p

This next part registers our [stars rating="2.5"] shortcode with WordPress so that WordPress knows that when we use this in an article, we really want to replace that with the result of our dm_stars_func() function. We also need to make sure that we enable shortcodes on our excerpts (just in case) as well on our comments. (For the stars shortcode, this probably isn’t necessary, but I included it since I use it on my main plugin – mostly because I have a ton of shortcodes (not just the stars one) and I want/need those available in the comments section too.)

// add our quicktags to the admin section
function dm_stars_quicktags()
{
	wp_enqueue_script('dm_stars_quicktags',plugins_url('',__FILE__).'/js/quicktags.js',array('quicktags'),false,true);
}

// add our quicktags to admin pages only
add_action('admin_print_scripts','dm_stars_quicktags');

This next block of code is just telling WordPress that we have a JavaScript file that we need to load on admin pages. The code that creates a new button in the toolbar of our post edit pages is all JavaScript, that’s why. And Here’s what that JavaScript file looks like:

// only add the buttons if we actually have a toolbar
if(dmquicktagsToolbar = document.getElementById("ed_toolbar")){
	var dmBut, dmNr;

	// add the Stars Button
	dmNr			= edButtons.length + 1;
	edButtons[dm_Nr]	= new edButton('ed_dmstars','Stars','','','',-1);
	var dmBut		= dmquicktagsToolbar.lastChild;
	while (dmBut.nodeType != 1)
	{
		dmBut		= dmBut.previousSibling;
	}
	dmBut			= dmBut.cloneNode(true);
	dmquicktagsToolbar.appendChild(dmBut);
	dmBut.value		= 'Stars';
	dmBut.title		= dmNr;
	dmBut.onclick	= dm_embed_stars;
	dmBut.id		= 'ed_dmstars';
}

function dm_embed_stars()
{
	var rating		= prompt('Enter the rating:','2.5');
	var type;
	if (rating)
	{
		type		= prompt ('Enter the label for the "Rating" (or blank for "Overall"):','');
		type		= (type) ? ' type="'+type+'"' : '';

		edButtons[parseInt(this.title)].tagStart = '\n[stars rating="'+rating+'"'+type+']\n';
		edInsertTag(edCanvas,parseInt(this.title));
	 }
}

Essentially what we’re doing is adding a "Stars" button to our toolbar and creating a function dm_embed_stars() that will run whenever that button is pressed. You can see that all it does is prompt us for the rating and the rating type and then uses that information to generate our shortcode and embed it into our article.

Pretty simple and basic, but hopefully it gives you a good starting point for your own plugin. Let me know what questions you have!