WordPress Custom Shortcode Tutorial (PHP Examples)

Learn how to create custom WordPress shortcodes from scratch in our step-by-step WordPress custom shortcode tutorial.

What are WordPress shortcodes?

Want to create a WordPress custom shortcode? WordPress shortcodes are simple and easy-to-use code snippets. They allow you to add complex functionality to your website with minimal coding knowledge. You write a shortcode as “tags” within square brackets (for example: [my_shortcode]). And, when inserted into your WordPress editor, they are replaced with a specific output. What’s so cool about them: you can create custom WordPress shortcodes to add unique features and functionality to your website. We’ll discuss this further in this post. Also, WordPress comes with a set of built-in shortcodes that you can use. They can add various elements to your website, such as galleries, audio and video players, and more.

Shortcode syntax

The WordPress shortcode syntax defines a set of rules that explain how you should write and use shortcodes. You always enclose shortcodes in square brackets []. Additionally, shortcodes may include attributes, which are additional parameters that modify the output of the shortcode, like this: [my_shortcode id="123"]. Shortcodes can also include content between the opening and closing shortcode tags, which the shortcode function will then process. We call these “enclosing shortcodes”, and they look like this: [my_shortcode]Enclosed content here[/my_shortcode]. Understanding shortcode syntax is crucial for effectively creating custom shortcodes for your WordPress website.

Shortcode attributes

Shortcode attributes are an essential aspect of custom WordPress shortcodes that provide additional parameters to modify the shortcode output. You can use attributes to customise the functionality and appearance of your shortcode by providing values for different parameters. Attributes consist of key-value pairs, separated by equal signs and enclosed within double quotes. You can add as many attributes as necessary to a shortcode. Each attribute can contain a variety of values, including text, numbers, and Boolean values. A shortcode with attributes can look like this: [my_shortcode id="123" text="something" boolval="true"]. Understanding how to use shortcode attributes is crucial for creating custom shortcodes that you can tailor to your needs.

Built-in shortcodes in WordPress

WordPress comes with a variety of built-in shortcodes that you can use to add various elements to your website. Those shortcodes are available right out of the box. This means you don’t have to write any code to use them. A list of shortcodes that come built in with WordPress, are:

  • audio
  • video
  • embed
  • caption
  • gallery
  • playlist

These shortcodes enable you to add media elements such as images, audio files, videos, captions, playlists, and more to your website without any additional plugins or code. Built-in shortcodes offer an efficient way to add richer and slightly more complex elements to your website. At the same time, they also save you time and effort in the process.

Why create a WordPress shortcode?

Using custom shortcodes in WordPress provides several benefits to website owners. Firstly, when you create a WordPress shortcode, you can add complex functionality to your website with minimal coding knowledge. Therefore, it can save you time and effort in the long run. Additionally, custom shortcodes offer a way to create a consistent design language across your website. That’s because you can use the same shortcode for similar elements. This makes it easier to maintain and update your website. You can now make changes to the shortcode function rather than changing individual elements on each page.

Custom shortcodes also provide a way to add unique features to your website that may not be available through built-in shortcodes or existing plugins. By creating custom shortcodes, you can add specific functionality tailored to your needs. This can help to differentiate your website from others. Overall, using custom shortcodes in WordPress can improve your website’s functionality, design, and user experience.

When to create a custom WordPress shortcode?

You can use custom WordPress shortcodes for a variety of purposes, depending on the specific needs of your website. Some common use cases for custom shortcodes include adding frequently used HTML elements, such as buttons or alert boxes. Another popular use case for custom shortcodes is to add unique functionality, such as a custom form or calculator. Also, anything that existing plugins or built-in shortcodes don’t provide for can be added manually!

You can also use custom WordPress shortcodes to embed media files, such as audio or video, onto your website or to create custom layouts for pages or posts. Ultimately, the use cases for custom shortcodes are limited only by your imagination and the needs of your website. By creating your own custom shortcodes, you can streamline your content creation process and add unique features that set your website apart from others.

How to add a WordPress shortcode to posts?

Shortcodes allow you to easily insert dynamic content or interactive elements into your posts, without requiring any advanced coding skills. However, if you’re new to WordPress, it can be challenging to know how to add shortcodes to your posts effectively.

To add a WordPress shortcode to your posts, the first step is to determine which shortcode you want to use. Themes or plugins can provide shortcodes, or you can create your own custom shortcode as we’ve discussed in previous chapters. Once you’ve identified the shortcode you want to use, you can simply insert it into the content of your post using the following syntax: [shortcode]. If the shortcode has any parameters, you can add them inside the opening and closing brackets, like this: [shortcode parameter1="value1" parameter2="value2"].

Once you’ve added the shortcode to your post, WordPress will automatically replace its content. It’s important to note that some shortcodes may not work as expected if they are used in certain contexts. For example, when written within a widget or a template file. In these cases, you may need to use a different method to include the shortcode in your content.

How to create a WordPress shortcode?

Creating a custom shortcode with WordPress can seem like a daunting task, but it’s actually very easy! In this chapter, we’ll explore how to create a custom WordPress shortcode step-by-step. We’ll identify the functionality you want to add, setting up your shortcode function, and adding your shortcode to your website. By the end of this chapter, you’ll have a solid understanding of how to create custom shortcodes and the benefits they can bring to your site.

Choosing a name when creating a custom WordPress shortcode

When creating a custom shortcode in WordPress, choosing the right name is an important first step. Your shortcode name should be descriptive and easy to remember, while also being unique to avoid conflicts with other shortcodes or functions. It’s a good idea to choose a name that reflects the function of your shortcode, such as [contact-form] for a custom contact form or [pricing-table] for a custom pricing table.

Also, it is important to follow WordPress coding standards when choosing your shortcode name, which typically involves using lowercase letters and hyphens to separate words. By choosing a clear and descriptive name for your shortcode, you’ll make it easier to use and remember for yourself and others who may be working on your website.

Create a custom shortcode PHP function

The shortcode function is the heart of your custom WordPress shortcode. This function defines the behaviour of your shortcode, including any content or functionality it provides. To create a shortcode function, you’ll need to define a function in your theme or plugin files, and use the add_shortcode() function to register it with WordPress. Within your shortcode function, you’ll typically use a combination of PHP, HTML, CSS, and JS. Here’s an example of registering a custom shortcode:

add_shortcode( 'my_shortcode', 'my_shortcode_function' );

function my_shortcode_function() {
	return 'Hello world!';
}

When the above shortcode [my_shortcode] is used within the content of a post or page, it will be replaced by the output Hello world!.

Create a shortcode with attributes in WordPress

Shortcode attributes are a powerful way to add flexibility and customisation to your WordPress shortcodes. With attributes, you can allow users to customise the behaviour of your shortcode based on their specific needs. By adding shortcode attributes to your custom shortcode, you can create a more versatile and user-friendly experience for your visitors. To add attributes to your shortcode, you’ll need to modify your shortcode function to accept the attributes as parameters. Within your shortcode function, you can then use these parameters to customise the behaviour of your shortcode. For example, by changing the color or text of a button or the number of columns in a layout.

add_shortcode( 'cool_button', 'my_shortcode_function' );

function my_shortcode_function( $attributes ) {

   $text = $attributes[ 'text' ] ?? 'Default text';

   return '<button>' . esc_html($text) . '</button>';
  
}

When using the above shortcode without passing any attributes to it, it will output the default value for the attributes. However, when calling the shortcodes with the attributes, we can change the text of the button.

[cool_button] 
// Outputs: <button>Default text</button>

[cool_button text="Click me"] 
// Outputs <button>Click me</button>

It’s important to sanitise and escape any user input when adding shortcode attributes, in order to prevent security vulnerabilities. You can use the built-in WordPress functions like sanitize_text_field(), esc_html(), or esc_attr() to sanitise the user input. Luckily, WordPress provides a great API for securing and escaping data.

Create a WordPress shortcode with content

In addition to accepting shortcode attributes, your custom WordPress shortcode may also need to handle any content within it. Shortcode content refers to any text, HTML, or other content that you enclose within the shortcode tags. The content that you add within a shortcode, can be output directly and unfiltered by the shortcode. Alternatively, you can manually parse and manipulate the content within your shortcode function using regular expressions or other PHP functions. Any shortcode content, is always passed as the second parameter to the shortcode callback function. Therefore, it is always a good practice to provide a default value for the second parameter to the callback function.

function my_shortcode_handler( $atts, $content = null )

An simple shortcode [wrapper][/wrapper] with enclosed content might look like this:

add_shortcode( 'my_wrapper', 'wrapper_shortcode_function' );

function wrapper_shortcode_function( $atts, $content = null ) {

	return '<div class="wrapper">' . $content . '</div>';
}

Like with attributes, when handling shortcode content, it’s important to ensure that your code is secure and properly handles input. You should also consider the performance of handling shortcode content. This is because parsing and manipulating large amounts of content can impact the performance of your website. By effectively handling shortcode content, you can create more complex and dynamic custom shortcodes for your WordPress site.

Enqueueing scripts and styles

When creating a custom shortcode that requires additional scripts or styles, it’s important to properly enqueue them in WordPress. Enqueuing scripts and styles ensures that they’re loaded in the correct order and only when they’re needed. This can drastically improve the performance of your site. To enqueue scripts and styles in WordPress, you can use the wp_enqueue_script() and wp_enqueue_style() functions, respectively. Ensure that your custom shortcode functions correctly and efficiently on your website, by properly enqueueing scripts and styles.

Create a WordPress shortcode (Example)

By creating custom shortcodes, you can provide users with tailored solutions for specific needs. This is a great way to improve the user experience and increasing engagement on your site. In this chapter, we’ll explore several real-world examples of custom WordPress shortcodes. From examining these examples, you’ll gain insight into the versatility and potential of custom shortcodes. You will also learn how to create your own custom shortcodes to meet the needs of your website and users.

Create a shortcode for WordPress without a plugin

One of the most common uses for custom shortcodes is to create simple formatting or styling options for your website. For example, you may want to create a custom shortcode that outputs specific content. Here are a few examples.

Create a WordPress shortcode that outputs text

add_shortcode( 'my_shortcode', function() {
    return 'Hello world!';
});

Custom WordPress shortcode that outputs HTML

add_shortcode( 'my_shortcode', function() {
    return '<div>HTML content here...</div>';
});

Create a WordPress shortcode that outputs a template file

To create a custom shortcode that outputs a template file, you’ll first need to create a template file that contains the HTML you want to display. Next, you’ll need to write the shortcode function and use the WordPress built-in function get_template_part() to retrieve the template file. In order to return the output (don’t use echo!), use ob_start() and ob_get_clean():

add_shortcode( 'my_shortcode', 'my_shortcode_callback' );

function my_shortcode_callback() {

	ob_start();

  get_template_part('call-to-action');

	return ob_get_clean();
}

WordPress custom shortcode with parameters

One of the most powerful features of custom shortcodes in WordPress is the ability to accept parameters. Effectively, this allows you to create flexible and dynamic functionalities for your website. With shortcode parameters, you can pass in values like text, numbers, or even other shortcodes, and use them to customise the output of your shortcode.

To create a custom shortcode with parameters, you can define the parameters within the shortcode function using the first parameter of the function (often defined as $atts which is short for ‘attributes’), which is an array of attribute values passed in from the shortcode tag. Within the function, you can use these attributes to modify the output of the shortcode as needed. A great way to set default values for attributes, is using the shortcode_atts() function.

add_shortcode( 'my_shortcode', 'my_shortcode_callback' );

function my_shortcode_callback( $attributes ) {

  $parsed_attributes = shortcode_atts( array(
		'id' => 'default_id',
		'slug' => 'default_slug,
	), $attributes );

	return 'ID is ' . $parsed_attributes['id'] . ' and slug is ' . $parsed_attributes['slug'];
}

Now, our custom shortcode can be used in a variety of ways.

[my_shortcode] // Outputs: 'ID is default_id and slug is default_slug'
[my_shortcode id='123'] // Outputs: 'ID is 123 and slug is default_slug'
[my_shortcode slug='hello-world'] // Outputs: 'ID is default_id and slug is hello-world'
[my_shortcode id='123' slug='hello-world'] // Outputs: 'ID is 123 and slug is hello-world'

Advanced techniques

Once you’ve mastered the basics of WordPress shortcodes, there are a variety of advanced techniques you can use to take your shortcode game to the next level. These techniques can help you create more complex and powerful shortcodes, integrate shortcodes with other plugins or APIs, and even build custom shortcode generators for your clients or users. In this chapter, we’ll explore some of these advanced techniques in depth. By the end of this chapter, you’ll have a solid grasp of some of the more advanced capabilities of WordPress shortcodes and be able to use them to create even more dynamic and engaging content for your WordPress website.

Shortcode nesting

Shortcode nesting is an advanced technique that allows you to combine multiple shortcodes within a single post or page. With shortcode nesting, you can create more complex and powerful functionality than is possible with a single shortcode alone. However, in order to nest shortcodes, you can not simply include one shortcode within the content of another shortcode.

add_shortcode('inner_shortcode', function(){
   return 'Hello world!';
});

add_shortcode( 'outer_shortcode', function( $atts, $content = null){
   return '<div class="outer">' . $content . '<div>';
});

// By default, this will output: <div class="outer">Inner shortcode says: [inner_shortcode]<div>'
[outer_shortcode]Inner shortcode says: [inner_shortcode][/outer_shortcode]

If you want an enclosing shortcode to accept nested shortcodes within the content, it’s necessary to output the content of the shortcode using the do_shortcode() function, like so:

add_shortcode('inner_shortcode', function(){
   return 'Hello world!';
});

add_shortcode( 'outer_shortcode', function( $atts, $content = null){
   return '<div class="outer">' . do_shortcode( $content ) . '<div>';
});

// Now, this will output: <div class="outer">Inner shortcode says: Hello world!<div>'
[outer_shortcode]Inner shortcode says:[inner_shortcode][/outer_shortcode]

Now, when the post or page is displayed, WordPress will automatically replace the inner shortcode with its corresponding content before replacing the outer shortcode with its own content. It’s important to note that not all shortcodes are designed to be nested, and some may not work correctly if they are used in this way. Additionally, nesting too many shortcodes within one another can cause performance issues and may make your content more difficult to maintain in the future. As with all advanced techniques, it’s important to use shortcode nesting judiciously and only when it makes sense for your particular use case.

Shortcode output buffering

Shortcode output buffering is an advanced technique that can be used to manipulate the output of shortcodes before it is sent to the browser. By default, when a shortcode is processed, its output is sent directly to the browser. However, with output buffering, the shortcode output is stored in a buffer and can be manipulated using PHP functions before being sent to the browser.

This technique can be useful for performing complex operations on shortcode output, such as modifying HTML tags or applying regular expressions to the content. To use output buffering with shortcodes, simply add the ob_start() function to the beginning of your shortcode function and the ob_get_clean() function to the end. These functions will start the output buffer and return its contents, respectively. As with all advanced techniques, it’s important to use shortcode output buffering carefully and only when it’s necessary to achieve your desired functionality.

Programmatically render shortcodes within template files

Sometimes you may want to programmatically render shortcodes within your WordPress template files. This can be useful if you want to display shortcode output within a particular location on your website or if you want to customise the way the shortcode output is displayed. To render a shortcode within a template file, you can use the do_shortcode() function. This function takes the shortcode as its parameter and returns the output generated by the shortcode. For example, if you want to display the output of a shortcode called [my_shortcode] within your template file, you would use the following code:

echo do_shortcode( '[my_shortcode]' );

This will render the shortcode output directly within your template file at the location where you place the above code. Using do_shortcode() function within your template files gives you a lot of flexibility in how you display shortcode output on your website.

Creating shortcode plugins

Creating a custom plugin for your shortcodes is a great way to reuse your custom shortcodes across multiple WordPress sites or to distribute them to others. A shortcode plugin is essentially a regular WordPress plugin, but instead of adding functionality to the WordPress site directly, it provides custom shortcodes that users can use in their content. To create a shortcode plugin, you can start by creating a new directory in the wp-content/plugins/ directory of your WordPress site. Inside this directory, create a new PHP file that will serve as the main plugin file. In this file, you can define your custom shortcodes using the add_shortcode() function.

/*
 * Plugin Name:       My plugin
 * Description:       This plugin adds the shortcodes [myplugin_abc] and [myplugin_xyz].
 * Version:           1.0.0
 */

add_shortcode( 'myplugin_abc', 'myplugin_shortcode_abc' );
add_shortcode( 'myplugin_xyz', 'myplugin_shortcode_xyz' );

function myplugin_shortcode_abc() {
  ...
}

function myplugin_shortcode_xyz() {
  ...
}

By creating shortcode plugins, you can simplify the process of adding custom functionality to WordPress sites and make it easier for others to use your custom shortcodes.

Using shortcodes in widgets

Using shortcodes in widgets can be a powerful way to add dynamic content to your WordPress site. To use a shortcode in a widget, you can simply add a “Text” widget to a sidebar or other widget area and then include your shortcode in the text area of the widget. Once the widget is saved, the shortcode will be rendered automatically and its output will be displayed in the widget area. However, not all shortcodes may work properly in widgets, as some may require additional resources or may not be designed to work within widget areas. It’s also important to note that some WordPress themes may limit the types of widgets that can be used in certain areas of the site. Despite these limitations, using shortcodes in widgets can still be a useful technique for adding custom functionality to your WordPress site.

Best practices and troubleshooting

As with any coding project, creating custom WordPress shortcodes can sometimes present challenges and issues. In this chapter, we will explore some best practices for creating and implementing custom shortcodes, as well as tips for troubleshooting common issues that may arise. By following these best practices and learning how to troubleshoot issues, you can ensure that your custom shortcodes are effective, efficient, and error-free, and that they provide the desired functionality for your WordPress site.

Always return output, never echo

When writing custom shortcodes in WordPress, it’s important to follow the best practice of always returning the shortcode output rather than echoing it. Returning the output allows WordPress to properly handle the shortcode content and integrate it into the post or page where it’s used, while echoing the output can cause unexpected behavior or errors. Additionally, by returning the output instead of echoing it, you can easily modify or manipulate the shortcode output in other parts of your code, allowing for greater flexibility and control over your website’s content.

Luckily, there are ways to ensure that your custom shortcodes always return their output, even when you want it to echo lots of HTML. You can use the PHP function ob_start() at the beginning of your shortcode function, and ob_get_clean() at the end, to capture the output and return it as a string. Following this best practice will help you create more reliable and effective custom shortcodes for your WordPress website.

WordPress best practices for custom shortcode development

When developing custom shortcodes for your WordPress site, it’s important to follow some best practices to ensure that they are effective, secure, and compatible with other plugins and themes. One of the most important best practices is to use a unique and descriptive name for your shortcode to avoid conflicts with other shortcodes. Additionally, it’s important to sanitize and validate any user input to prevent security vulnerabilities.

It’s also a good practice to enqueue any necessary scripts and styles for your shortcode instead of hard-coding them directly into your shortcode function. Finally, it’s important to test your shortcode thoroughly on different browsers and devices to ensure compatibility and to make sure it is rendering correctly. By following these best practices, you can create custom shortcodes that are robust, secure, and provide the desired functionality for your WordPress site.

Common shortcode issues and how to fix them

While custom shortcodes can be a powerful tool to add functionality to your WordPress site, they can also come with some common issues that you may encounter. One of the most common issues is when the shortcode is not rendering properly, which can be caused by a variety of factors such as conflicting code, missing or incorrect syntax, or a problem with the shortcode function. Another issue can be the incorrect or unexpected output of the shortcode. An incorrect parameter value or a lack of proper error handling in the shortcode function can cause these issues.

Additionally, it’s important to ensure that your shortcode is compatible with different WordPress themes and plugins, as some may have their own shortcode handlers or may be using conflicting code that can cause issues with your custom shortcode. To troubleshoot these issues, you can use WordPress debugging tools, review the shortcode syntax and function, and test the shortcode with different themes and plugins to identify and resolve any conflicts.

WordPress custom shortcode not working?

Here’s a simple checklist you can follow to debug WordPress shortcodes:

  • Is the place you are calling your shortcode from supporting the use of shortcodes?
  • Does your shortcode have a unique name?
  • Is the shortcode function name unique?
  • Are you using return to render the output instead of echo?
  • Have you included the file where you are adding your shortcode correctly?
  • Is the plugin that includes your shortcode installed and activated?
  • Does your site run on the required version of PHP?

Debugging your custom shortcode

Debugging custom shortcodes is a crucial step in the development process. It allows you to identify and fix issues that may be affecting the functionality of your shortcode. One way to debug your custom shortcode is by using var_dump() or die(). These functions will display the content of a variable, allowing you to see what data is being passed to your shortcode. Additionally, it is important to test your custom shortcode thoroughly before deploying it to a live site. This will ensure that it functions as intended and does not cause any issues for your site visitors.

Conclusion

In conclusion, custom WordPress shortcodes are a powerful tool. They can help developers and website owners improve the functionality and user experience of their sites. By creating custom shortcodes, you can easily add complex functionality to your posts and pages. Shortcodes can be used without the need for additional plugins or code. However, it is important to follow best practices when developing custom shortcodes. Also, thoroughly test and debug shortcodes before using them on a live site. By doing so, you can ensure that your shortcodes function as intended and do not cause any issues. With the knowledge and techniques covered in this guide, you should be well-equipped to create and implement custom shortcodes in your WordPress site! Feel free to ask any questions in the comments below, or reach out for any help!

Last updated on May 17, 2023. Originally posted on April 30, 2023.

Leave a Reply

Your email address will not be published. Required fields are marked *