Popular Categories

How to make WordPress shortcodes?

Shortcodes look like a small piece of text within square brackets, something like this: [shortcode]. It triggers on demand as you view your content. They are a popular feature included in many plugins and themes which can be used almost anywhere, even between the text. However, if you’ve never built your own shortcodes before, you may have no idea how to add them to your own WordPress projects.

Thankfully, WordPress’ makes it fairly simple to create your own shortcodes. Here is an example with the snippet of code that will help you create your own shortcode that will output “Hello World!” once you use it.

The first step is writing your own function that outputs what is desired from the shortcode. In our case, we will return “Hello world!” if someone uses [helloworld] as a shortcode.

function hello_world_shortcode() {
   return 'Hello world!';

Once the function is created, lets integrate it with WordPress by using addons:

// Note first parameter is the name of the short while the next one is the function name
add_shortcode( 'helloworld', 'hello_world_shortcode' );

Add both the above snippets to function.php file and you are done : ) Incase you plan to use the shortcode which accepts attribute values like in the above case it could be the name. Example: [helloworld name=”Shah”] so it outputs “Hello Shah!”. Here is how the above code can be rewritten:

function hello_world_shortcode( $atts ) {
   $a = shortcode_atts( array(
      'name' => 'world'
   ), $atts );
   return 'Hello ' . $a['name'] . !';
add_shortcode( 'helloworld', 'hello_world_shortcode' );

Add-On: Getting Shortcode Work in a Widgets

You also can’t get shortcode to work in widget areas by default, however a filter can be added to the functions.php file to make that work

// Use shortcodes in text widgets.
add_filter('widget_text', 'do_shortcode');

With shortcodes, adding complex functionality to WordPress posts and pages is now very easy. They are simple to program and add value to your existing project. What questions do you have about using the Shortcode API? Let us know in the comments section below!

Was this helpful? Did I missed something? Do you have a question? Get in touch.