Creating a Custom WordPress Shortcode

Creating your own WordPress shortcodes is a nifty way to build dynamic elements into your website without relying on 3rd party developers or plugins. This tutorial offers a beginner’s guide to creating your first WordPress plugin which will be referenced by a custom shortcode.

In this example we’ll be creating a basic random quote generator plugin. This can just as easily be achieved through your themes functions.php but I prefer to be able to turn items on and off in WordPress without having to edit blocks of code.

Creating the WordPress Plugin File

If you’re familiar with WordPress plugins and have installed them before, you’ve probably seen folders chock full of complicated PHP classes. This is not necessary for a working plugin; something as simple as a quote generator only needs 1 file. Create your plugin file (in this example we’ll call it gwg_quote.php) and enter the following base info:

<?php
/*
	Plugin Name: gwg Random Quote Generator
	Plugin URI: http://girlswhogeek.com/?p=154
	Description: Basic custom WordPress plugin example: random quote generator
	Version: 1.0
	Author: Girls Who Geek
	Author URI: http://girlswhogeek.com
	License: GPL2

	Copyright 2011 GirlsWhoGeek  (email: jem@girlswhogeek.com)

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License, version 2, as 
	published by the Free Software Foundation.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

This is the required plugin info which will be used to populate the WordPress plugins page, and the license information. In this instance we’re using GPL2 because a) it’s what WordPress uses and b) I am a big fan of free code :)

Creating the Plugin Function

Although WordPress supports classes (and encourages their use to prevent naming clashes) it’s too big a subject for the scope of this plugin. Creating a basic PHP function is plenty sufficient. If you’re unfamiliar with the syntax for creating a function with PHP, or have never heard of scope before, I recommend reading PHP Beginner’s Guide Part Six on my development blog (off site).

And so we add the barebones of the function underneath the previously entered licencing information:

<?php
/*
	[license info]
*/

function gwg_random_quote_generator() {

}

I’ve used a descriptive name for the function to make it easier to find/modify later on, and prefixed the function with gwg_ to avoid naming clashes briefly mentioned earlier.

It’s worth noting at this point that if we wanted to create a WordPress shortcode via which we’d pass arguments, e.g. [foo id=#], we’d need to pass an array of attributes to the function. We don’t need this functionality, and as the shortcode will work without it, I’ve left it out for simplicity’s sake. Moving swiftly on…

Inside our new (currently empty) function we place the code which powers the functionality we wish to achieve when we use our shortcode; our random quote generator (you may recognise the code from an old tutorialtastic tutorial…)

<?php
/*
	[license info]
*/

function gwg_random_quote_generator() {
	// define our array 
	$quotes = array();
	
	// populate with quotes
	$quotes[] = "A superior man is modest in his speech, but exceeds in his actions.";
	$quotes[] = "Do not impose on others what you yourself do not desire.";
	$quotes[] = "An ounce of practice is worth more than tons of preaching.";
	
	// generate a random number between 0 and the total count of $quotes minus 1
	// we minus 1 from the total quotes because array indices start at 0 rather than 1 by default
	$r = rand(0,count($quotes)-1);
	
	// return the quote in the array with an indices of $r - our random number
	return $quotes[$r];
}

Now that we have the meat of the plugin in place, we can use the WordPress add_shortcode to specify our custom shortcode: add_shortcode( 'randomquotes', 'gwg_random_quote_generator'); This enables us to use Do not impose on others what you yourself do not desire. in posts and pages, which WordPress will apply the gwg_random_quote_generator function too.

Altogether now:

<?php
/*
	Plugin Name: gwg Random Quote Generator
	Plugin URI: http://girlswhogeek.com/?p=154
	Description: Basic custom WordPress plugin example: random quote generator
	Version: 1.0
	Author: Girls Who Geek
	Author URI: http://girlswhogeek.com
	License: GPL2

	Copyright 2011 GirlsWhoGeek  (email: jem@girlswhogeek.com)

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License, version 2, as 
	published by the Free Software Foundation.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

function gwg_random_quote_generator() {
	// define our array 
	$quotes = array();
	
	// populate with quotes
	$quotes[] = "A superior man is modest in his speech, but exceeds in his actions.";
	$quotes[] = "Do not impose on others what you yourself do not desire.";
	$quotes[] = "An ounce of practice is worth more than tons of preaching.";
	
	// generate a random number between 0 and the total count of $quotes minus 1
	// we minus 1 from the total quotes because array indices start at 0 rather than 1 by default
	$r = rand(0,count($quotes)-1);
	
	// return the quote in the array with an indices of $r - our random number
	return $quotes[$r];
}

add_shortcode( 'randomquotes', 'gwg_random_quote_generator');
?>

Save to the gwg_quote.php file you created earlier and upload to /wp-content/plugins/. Once the plugin is enabled via your WordPress admin panel, test it out by popping [randomquotes] into a post or page, and Bob’s your uncle:

A superior man is modest in his speech, but exceeds in his actions.

One basic WordPress plugin with shortcode.

Comments

  1. everdare says:

    “Once the plugin is enabled via your WordPress admin panel, test it out by popping A superior man is modest in his speech, but exceeds in his actions. into a post or page, and Bob’s your uncle” might not quite be what you meant. :)

  2. LMAO – of course, it didn’t occur to me that my example would be activated when I actually installed the plugin. Cheers ;)

  3. oh nifty :D I’ve always wanted to make my own plugin for something (don’t remember what it was o.O ). ‘Course I never get anything done that I plan on doing :P

    I will totally bookmark this though just in case ;)

  4. have not tinkered with this, but this page could help me implement the quote-generator (with my quotes) that’s I’ve wanted to make for years!

  5. How would you implement this the [randomquotes] on a widget? So far it works on non-widgets EXCELLEnT!!!!!!

  6. Thanks so much for this – kind of what I’m looking into to start making my own WordPress plugin :)

  7. Codegrrl helped me in so many ways. I started coding when I was 16 and 11 years later I’m working full time as a graphic / web designer. If it weren’t for sites like codegrrl and you ladies I may not have worked out that way for me. So I hope that inner code passion strikes again soon and you find a chance to return to the web! but either way I wanted to thank you :)

  8. So glad this came up for me in Google! I’m just getting to grips with shortcodes and they’re still making my head hurt, but this was exactly what I needed, thanks :)

  9. Nice! It worked perfectly. Even when querying the database! But the queried content is displayed above content from my page/post.

    Is there something I can do to change this?

    • This usually occurs when you ‘echo’ from within the shortcode instead of assigning the data to a variable and returning it. What I tend to do is the following…

      $data = ‘this is the first line of my shortcode stuff’;
      $data .= ‘this might be the result of a query or similar’;
      $data .= ‘some more stuff to return’;

      return $data; // now returning the data, rather than echoing it individually

      Does that make sense?

Trackbacks

  1. [...] Creating a Custom WordPress Shortcode: making a basic WordPress plugin displayed via shortcode [...]

  2. [...] Creating a Custom WordPress Shortcode: making a basic WordPress plugin displayed via shortcode [...]

Add Comment Register



Speak Your Mind

*