This forms part of my WordPress Plugin Development Series. In this section we add Shortcodes to a plugin.
Our Shortcode
We want to create a Shortcode that shows the current date to any section where the Shortcode is called.
Hooking your shortcode
Add the following code to your WordPress Plugin.
function wt_show_date_function(){
$currentDate = date('Y-m-d H:i:s');
return $currentDate;
}
add_shortcode('wt_show_date', 'wt_show_date_function');
When we break down the following line:
add_shortcode(‘wt_show_date’, ‘wt_show_date_function’);
We are simply telling wordpress to run our function – wt_show_date_function whenever our shortcode [wt_show_date] is called.
Take Note
You should always return any content you wish to display with Shortcodes.
If you tried to echo your content generated by your Shortcode instead of returning it, it would always appear before your content. So trying to use your Shortcode in the middle of a page would fail.
Full Code
Once you added the above, Your full plugin file should look as follows:
<?php
/* Plugin Name: WT Hello World
WordPress Plugin Development
description: Hello World WordPress plugin that alerts text via shortcode
Version: 1.0.2
Author: Willie Theron
Author URI: http://willietheron.com
License: GPL2 */
function wt_hello_world_activate() {
//This will run when your plugin is activated
}
register_activation_hook( __FILE__, 'wt_hello_world_activate' );
function wt_hello_world_deactivate() {
//This will run when your plugin is deactivated
}
register_deactivation_hook( __FILE__, 'wt_hello_world_deactivate' );
function wt_hello_world_uninstall() {
//This will run when your plugin is uninstalled
}
register_uninstall_hook( __FILE__, 'wt_hello_world_uninstall' );
//Shortcode to echo the date
function wt_show_date_function(){
$currentDate = date('Y-m-d H:i:s');
return $currentDate;
}
add_shortcode('wt_show_date', 'wt_show_date_function');
?>
Testing your plugin
Once your plugin has been updated, add your Shortcode to a sidebar, widget or page to test if it works.
I added my shortcode:
[wt_show_date]
to an empty page and it was working.
If you succeeded you will see the date, if you made a mistake, you would see the text [wt_show_date].
If you need it, here is the Source Code: wt-hello-world