WordPress Tutorial: ShortCode for Plugins

In today’s tutorial I will show you how to make a shortcode for WordPress plugin that can be used in posts and pages in WordPress. We will use a file named my_first_shortcode.php. Every new plugin you make starts with a header in php file. All important information about the plugin like name, author, version and author’s website are listed here. Below is an example of a header of php file:

Download source files for WP ShortCode (17)

/*
Plugin Name: My first shortcode
Plugin URI: http://premiumcoding.com
Description: My first shortcode
Version: 1.0
Author: Premiumcoding
Author URI: http://premiumcoding.com
Copyright 2011, PremiumCoding
*/

We will now implement a function with which we will call our shortcode:

function wp_myCustomShortCode (atts){
extract(shortcode_atts(array(
'name' => 'PremiumCoding',
), $atts));
}

We added an extra paramater to our function that we conveniently named “name”. We will use it later for writing purposes. Since our shortcode is very simple all our function will return is “My name is” and parameter $name. To achieve this we have to add following line:

$string = 'My name si' . $name .'.';

All we have to do now is return the result:

return $string;

Our function now looks like this:

function wp_myCustomShortCode (atts){
extract(shortcode_atts(array(
'name' => 'PremiumCoding',
), $atts));
$string = 'My name si' . $name;
return $string;
}

All we have to do now is add shortcode for usage in WordPress posts and pages:

add_shortcode('myCustomShortCode', 'wp_myCustomShortCode');

And our simple WordPress plugin with shortcode is now complete. We can call the plugin in posts and pages by using following shortcode:

[myCustomShortCode name=PremiumCoding] will return “My name is PremiumCoding.”

We can add a parameter with a custom name to the shortcode like this:

[myCustomShortCode name=myName] will return “My name is myName.”

File my_first_shortcode.php has to be saved in directory my-code. We now zip the file. Plugin can be uploaded and installed in a standard way. Just go to the Plugins section and select Add New. Click upload and select your zip. After plugin is installed simply click Activate and you are ready to use your newly created plugin with the shortcode. You are now ready to start making shortcodes for your WordPress plugins.

Comments are closed.