Makers Byte
Published in

Makers Byte

How to make WordPress shortcode?

Learn through the basics of WordPress Shortcodes. The post answers all the pin points needed to create your own WordPress Shortcodes

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!

Did we missed anything, if so leave it as a comment :)

If you enjoyed this post…it would mean a lot to me if you could click on the “claps” icon…up to 50 claps allowed — Thank You!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shahzaib Khan

Shahzaib Khan

138 Followers

Data Scientist, Developer, Tech Writer, Entrepreneur and Computer Science Enthusiast. Connect with me @ https://linkedin.com/in/shahzaibkhan/