Create a simple WordPress Plugin with Shortcode

Tags:

Creating a WordPress plugin from scratch can be intimidating, but it doesn’t have to be.

Here, we’ll show you how simple it is to create your own WordPress plugin with a shortcode to display some content.

  1. Get started! 

    Create a folder on your development machine, and create a blank .php file with the same name as the folder:

  2. Add the Header.

    Open the PHP file in your text editor of choice, and paste in the header section of the Plugin:

    <?php
    /**
     * Plugin Name: TBare Wodpress Plugin demo
     * Plugin URI: https://www.tbare.com
     * Description: Display content using a shortcode to insert in a page or post
     * Version: 0.1
     * Text Domain: tbare-wordpress-plugin-demo
     * Author: Tim Bare
     * Author URI: https://www.tbare.com
     */

  3. Add the function that will return the info.

    For this example, we’ll create a simple <h3> with a custom class, and style that class to have a green color. The function name should be unique as to not conflict with other plugins, as should the shortcode name.

     function tbare_wordpress_plugin_demo($atts) {
    	$Content = "<style>\r\n";
    	$Content .= "h3.demoClass {\r\n";
    	$Content .= "color: #26b158;\r\n";
    	$Content .= "}\r\n";
    	$Content .= "</style>\r\n";
    	$Content .= '<h3 class="demoClass">Check it out!</h3>';
    	 
        return $Content;
    }
  4. Register the shortcode

    Now we’ll add the code that registers the shortcode so WordPress knows what to do with it when it sees it in content. Here we’ll use the shortcode ‘tbare-shortcode-demo’to show the contents returned in the function we created in step 3:

    add_shortcode('tbare-plugin-demo', 'tbare_wordpress_plugin_demo');
  5. Save, Zip, and upload!

    You’re probably aware, but the easiest way to install a plugin is to upload a zip file. So, Zip up the entire folder you created in step up, upload it to your site — (‘Plugins’ > ‘Add New’ in case you’re not aware where to go).(don’t forget to activate it after you install it) :)

  6. Test it out.

    Add the shortcode into your page or post, and watch see how it works!

 

Here’s the full code from the pieces above:

<?php
/**
 * Plugin Name: TBare Wodpress Plugin demo
 * Plugin URI: https://www.tbare.com
 * Description: Display content using a shortcode to insert in a page or post
 * Version: 0.1
 * Text Domain: tbare-wordpress-plugin-demo
 * Author: Tim Bare
 * Author URI: https://www.tbare.com
 */
 
 function tbare_wordpress_plugin_demo($atts) {
	$Content = "<style>\r\n";
	$Content .= "h3.demoClass {\r\n";
	$Content .= "color: #26b158;\r\n";
	$Content .= "}\r\n";
	$Content .= "</style>\r\n";
	$Content .= '<h3 class="demoClass">Check it out!</h3>';
	 
    return $Content;
}

add_shortcode('tbare-plugin-demo', 'tbare_wordpress_plugin_demo');

 

And here’s the results on this page:

Check it out!

Top