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.
function button_shortcode($atts) {
}
Now create a variable and name it anything you like e.g: $data
then add required data as an array inside shortcode_atts()
.
$data = shortcode_atts(array(
'link' => '', // you can add default link here
'text' => '', // you can add default title here
), $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_url
, esc_attr
and esc_html
where needed.
$output = '<a href="'.esc_url($data['link']).'" class="btn btn-default">'.esc_html($data['text']).'</a>';
return $output;
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.
add_shortcode('button', 'button_shortcode');
Here is the full code all together in case you want to copy it.
function button_shortcode($atts) {
$data = shortcode_atts(array(
'link' => 'http://www.xecreators.pk',
'text' => 'XeCreators',
), $atts);
$output = '<a href="'.esc_url($data['link']).'" class="btn btn-default">'.esc_html($data['text']).'</a>';
return $output;
}
add_shortcode('button', 'button_shortcode');
That’s all, now you can add it your WordPress website using the following method anywhere in posts and pages.
[button link="http://www.xecreators.pk" title="XeCreators"]
If you want to hard-code the shortcode in your theme or plugin then use the do_shortcode()
function.
echo do_shortcode('[button link="http://www.xecreators.pk" title="XeCreators"]');
Muhammad Zohaib