+92 308 5039935
Get a Free Quote
+92 308 5039935

How to Create Shortcode in WordPress

How to Create Shortcode in WordPress

Shortcodes are very helpful in WordPress for adding custom code inside posts or pages. Although you can use drag-n-drop builders (e.g: WPBakery Page Builder, Elementor etc.) but still there comes time when we need to add custom code and shortcodes are the best options out there. In this post we are going to create a simple shortcode for button but it doesn’t mean you are limited, you can insert or create any type of element you can think of. You can find a detailed documentation on shortcodes at WordPress Codex but if you are looking for simple and short tutorial then lets begin.


First we need to a function. Lets create a function and name it button_shortcode() with $atts argument.


Now create a variable and name it anything you like e.g: $data then add required data as an array inside shortcode_atts().


Add the output html code to a variable e.g: $output and add data using the $data array. Then return that variable in your function. Remember to use esc_urlesc_attr and esc_html where needed.


Use add_shortcode() to initialize/add the shortcode. this function needs two attributes first is the shortcode name and second is the function you’ve created for the shortcode.


Here is the full code all together in case you want to copy it.


That’s all, now you can add it your WordPress website using the following method anywhere in posts and pages.


If you want to hard-code the shortcode in your theme or plugin then use the do_shortcode() function.


Hello, I am a web designer and developer working since 2013. I build WordPress themes, write and extend WordPress plugins, edit WordPress themes and plugins in accordance to customer needs and play games when free ;-)
Related Post
Minify CSS
How to minify CSS in WordPress Theme or Plugin

Minification is used to remove unnecessary elements, e.g: extra spaces. There are a lot of php scripts to minify or compress the css but we are going to use a simple function  here. It is usually used for inline css in WordPress.

Read more
How to add inline CSS in WPBakery Page Builder Element

WPBakery Page Builder (Formerly Visual Composer) is one of the best drag and drop front-end/back-end builder. You can easily apply inline css using style attribute but what if you need to apply css to a pseudo elements?

Read more
How to Auto Load Files in WordPress?

You may need to auto load files in WordPress themes or plugins. But I wouldn’t recommend it if you are creating theme to sell on themeforest. They didn’t accepted themes with this auto load function few years ago when we used

Read more

Leave a Reply

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