How to Create Shortcode in WordPress

Have you ever needed to run or display the result of your custom PHP code on your WordPress website posts or pages? Since by default WordPress doesn’t allow you to run PHP in posts or pages for security precautions, you might have considered using a plugin to enable the use of PHP code on your post or pages. Actually, you can run the code without installing any additional plugins, just by creating a shortcode you can add the code on a separate PHP file or you can place the code in your theme functions.php file and then use the shortcode you’ve created to display the result on your website posts or pages!

What is Shortcode?

Introduced with the release of the Shortcode API from WordPress 2.5, shortcode allows you to add features with minimal effort that normally would require lots of complicated code in just one line within a square bracket, like [thisone]. Shortcodes used to be offered by a lot of WordPress plugins to drastically simplify the process of displaying the result of a complex function. For instance, a popular eCommerce plugin like WooCommerce also has several premade shortcodes that can be very useful for any store owner using this platform.

However, Since the block editor (Gutenberg) replaced the classic editor, a lot of plugins have begun to offer blocks as it is easier and has a nice visual layout. But, if you have coding knowledge or you have some code to add additional features to your site, using shortcodes is still one of the best options you can try! And you can read our previous article about adding an estimated reading time to your blog posts using a shortcode in Gutenberg, Elementor, and Divi.

In this tutorial, we will show you how to create a shortcode in WordPress

How to Create a Shortcode

Before creating a shortcode, we suggest taking a backup of your site and using a child theme to avoid breaking the parent theme or losing your changes when you update your theme since we will add the code to the theme functions.php file. To open the file, navigate to Appearance Theme File Editor from your WordPress admin dashboard. On the appearing page, click on the Theme Functions(functions.php) from the Theme Files list to open the file editor.

Alternatively, you can create a separate PHP file in your theme folder (located at wp-content themes “Your Theme” in most cases) with myshortcodes.php as its name.

Once you created the file, you can add as many codes and shortcodes as you want between the PHP delimiter(<?php ?>) at that file. Then you just need to add one line of code at the bottom of your theme functions.php file to tell the system to include any changes you make to your shortcode file. And the code is as follows:

include('myshortcodes.php');

Creating a Basic Shortcode (Self-closing Shortcode)

Step 1: Prepare the Code

Once you’re ready, prepare the code you want to make into a shortcode. The code must have a function and return with no side effects as a shortcode is essentially a filter. You can create a simple PHP function to store sentences or links that can be called anytime by shortcode like follows:

function wpbfollow() {
Follow us on <a rel="nofollow" href="https://twitter.com/wp_pagebuilders">Twitter</a>';
}

For this tutorial, we use a PHP code to get the word count and calculate the estimated reading time by dividing the word count by 260 which is the average number of words adult silent read per minute. Then return the estimated time and the word count in one phrase like follows:

  • “1 minute read (word count 121)”

Place the following code at the bottom of your theme functions.php

function reading_time() {
$content = get_post_field( 'post_content', $post->ID );
$word_count = str_word_count( strip_tags( $content ) );
$readingtime = ceil($word_count / 260);
$wcounttext = " (word count ". $word_count .")";
if ($readingtime == 1) {
$timer = " minute read";
} else {
$timer = " minutes read";
}
$totalreadingtime = $readingtime . $timer . $wcounttext;
return $totalreadingtime;
}

Step 2: Create a Shortcode

The next step is to create a shortcode for the code you’ve prepared. To create a shortcode you may need to follow the following guideline to avoid an error:

  • Use the add_shortcode( string $tag, callable $callback ) to add a shortcode whereas the $tag is your shortcode name to be searched in post content and the $callback is to call the code you’ve prepared
  • Shortcode names should be all lowercase (number and underscore are accepted)
  • Avoid using a hyphen (-)
  • Add a prefix to make your shortcode name unique to avoid collision with another plugin shortcode.

Once you’re ready, create a shortcode for your code by using the add_shortcode and add your shortcode name and a callback for your code into its parameter like the following example:

add_shortcode('wpbread', 'reading_time');

The above shortcode is for the estimated reading time code from step 1. We use 'wpbread' for the shortcode name and the 'reading_time' callback which is our function name after. Continue by adding the above code just below the code you’ve prepared from step 1 in the functions.php file or in your custom PHP file then save the changes you’ve made to it.

Step 3: Using the Shortcode

Once the shortcode is ready, in our case the shortcode is [wpbread], now let’s try to call it in one of your posts by adding the shortcode just above the content or anywhere you choose to display it inside your content editor.

Now, let’s take a look at the front-end result either by previewing or publishing the post.

As you can see from the above screenshot, just above our content there is an estimated reading time that says “11 minutes read (word count 2775)” for the article we wrote.

Creating Shortcode with Attribute

Before start creating shortcodes with an attribute, you may want to read the shortcode creation guideline from the basic shortcode tutorial to avoid errors.

Shortcodes can accept parameters known as attributes to customize their behavior. To use a shortcode with an attribute, you need to add $atts to your handler function:

  • function shortcode_function($atts)

For example, we will show you how to create a shortcode that can display different sentences based on the attribute value you’ve inputted into the shortcode attribute.

Step 1: Get the Code Ready and Create the Shortcode

Before you can add a shortcode with an attribute to your posts or pages, you need to get your handler function ready and create the shortcode first. You can write down your code on your theme functions.php file, or you can put it in a separate file. Here is the code we used to create our shortcode with the attribute.

add_shortcode('wpbpr', 'wppriority');
function wppriority($atts = array()){
	shortcode_atts(array(
        'att1' => 'default1',
        'att2' => false
    ), $atts);
	if (!empty($atts)){
    	switch( $atts['att1'] ){
    case 'first': 
        $output = 'First attribute result is here!';
        break;
    case 'second': 
        $output = 'Second attribute result is being displayed!';
        break;
    default:
        $output = 'Default attribute is here!';
        break;
}
		return $output;
	}else {
	return "Please specify an attribute";
	}	
}

The code above will create the [wpbpr] shortcode and declare a handler function called wppriority() for the shortcode. The handler function will check if you have added an attribute to the shortcode, if not then it will return a “please specify an attribute” notice.

Once you’re using the correct attribute, then it checks for the value of the attribute and returns the corresponding result. And if the attribute is not correct or the value is not “first” or “second” then it will return “Default attribute value is here!” instead.

Step 2: Using a Shortcode with Attribute

Moving to your blog editor by editing a post or a page, add the attribute inside its square bracket when you use the shortcode. Here is an example of a shortcode using an attribute:

  • [wpbpr att1=”first”]

By using the above shortcode, we got the result as follows on our page:

And if we change the attribute value to the “second” like follows:

  • [wpbpr att1=”second”]

The result will change according to the “second” value as follows:

Creating an Enclosing Shortcode

Enclosing content with a shortcode allows you to manipulate the content using your handler function.

  • [myshortcode] your content [/myshortcode]

If you have read the basic shortcode creation guideline and you want to create an enclosing shortcode, you just need to add $content = null to the function of your shortcode. like follows:

  • function shortcode_function( $atts, $content = null )

To show you how to create one, we will create a shortcode that uses <a > tag where you will input an URL as its attribute and write its content between the enclosing shortcode to make the content clickable links.

  • [linkshort link=”https://twitter.com/wppagebuilders”]Twitter[/linkshort]

Once we’ve added the above shortcode to our editor, the front end result on our browser is like follows:

To achieve that, add the following PHP code inside your theme’s functions.php or inside a separate file PHP file that stores your custom shortcode.

function shortcodelink($atts = array(), $content=null){
	shortcode_atts(array(
		'link'=>'default'
	),$atts);
	$content=do_shortcode($content);
	if (!empty($atts)){
	 return 'Follow us on <a rel="nofollow" href="'.($atts['link']).'" style ="color:#7CB9E8;"> '.$content.'</a> to get more updates.';
	}else {
	return "Please add the the link attribute!";
	}	
}
add_shortcode('linkshort', 'shortcodelink');

The code above will create the [linkshort] shortcode and declare a handler function called shortcodelink() for the shortcode. The handler function will check if you have added an attribute to the shortcode, if not then it will return a “Please add the the link attribute!” notice. Once you’ve added the code, save you’re changes and the shortcode is ready for some action.

The Bottom Line

By default, WordPress doesn’t allow you to run PHP in posts or pages for security reasons. However, just by creating a shortcode, you can add the code on a separate PHP file or place the code in your theme’s functions.php file and then use the shortcode you’ve created to display the result on your website posts or pages without installing any additional plugins. A shortcode allows you to add features with minimal effort that normally would require lots of complicated code in just one line.

Since the block editor (Gutenberg) replaced the classic editor as a way of publishing content in WordPress, a lot of plugins have begun to offer blocks as it is easier and has a nice visual layout. However, if you have coding knowledge or you have some code to add additional features to your site using shortcodes is still one of the best options you can try!

This page may contain affiliate links, which help support WP Pagebuilders. Learn more

Leave a Comment

Pin It on Pinterest

Thanks for commenting

Help us grow by sharing this post with your friends!

10+ free Elementor landing page templates. No extra plugin!

Creating with WordPress?​

Subscribe and join 1,500+ WordPress users receiving tips and insights on creating with WordPress in the no-code era. At WP Pagebuilders, we write about the following topics a lot.