Write a Super Simple WordPress Plugin With Shortcode
In this example, I show how you can access your custom plugin using shortcode. The function displays a message to the screen. It only shows up if you insert shortcode onto the page.
What is a Shortcode?
A shortcode is some words between [] like [mycode]. The phrase "mycode" would be linked to activating a function in a plugin.
To link some shortcode to a function, you use add_shortcode() which is an already built in function.
add_shortcode('your_shortcode_name' , 'your_function_without_parentheses');
You can see my full example if you scroll down a bit.
What the Code Does
All the function does is display a text message with h2 styling.
The shortcode accesses the function and tells WordPress to insert it on the page where you typed in the shortcode.
Display Message Plugin With Shortcode
shortcode_example_plugin.php (make sure to zip before you upload and activate)
<?php
/*
*Plugin Name: Shortcode Example Plugin
*description: Use a shortcode to display a message
*Version: 1.1
*Author: Crystal Laing
*Author URI: www.crystallaing.com
*/
function demo_message (){
$message = "<h2>Shortcode Message Successful </h2>";
return $message;
}
// shortcode for "demo_message" function is "message_sc"
add_shortcode('message_sc', 'demo_message');
Then on your sample page, insert the shortcode [message_sc] into a text editor. (I'm using Elementor.)
Preview the page and sigh with relief that it worked.