How to Create Custom Shortcode in WordPress

WordPress introduced the shortcode API six years ago with the release of WordPress 2.5. Shortcodes are now used by a large number of WordPress plugins to allow users to add content to their posts and pages.

The shortcode API allows you to create your own shortcodes by adding functions to your theme functions.php template Example location is: http://www.yourwebsite.com/wp-content/themes/yourtheme/functions.php

Before you begin, please make sure you make a backup of functions.php and any other files you edit before making changes with your live website.

Please remember that shortcodes should be created for content and functionality that you use frequently. The whole point of using shortcodes is to save someone time. If you are only going to use something once, there is not much point in creating a shortcode for it.

To do this, I could add a function such as this to my theme’s functions.php template:

Example Code for Create Custom Shortcode

/** Button Shortcode */
function brtheme_button($atts, $content = null) {
extract(shortcode_atts(array(
‘link’ => ‘#’,
‘type’ => ‘normal’,
‘bgcolor’ => ”,
‘textcolor’ => ”,
‘target’ => ”,
‘lightbox’ => ”,
‘tooltip’ => ”
), $atts));

$out = ”;

$out .= ‘<a href=”‘ . $link . ‘”‘;

$out .= ‘ class=”button btn-‘ . $type . ”;

if ($tooltip != ”) {
$out .= ‘ link_tooltip’;
}

$out .= ‘”‘;

if ($bgcolor != ”) {
$out .= ‘ style=”background-color:’ . $bgcolor . ‘;’;

if ($textcolor != ”) {
$out .= ‘ color:’ . $textcolor . ‘;”‘;
}
}

if ($bgcolor == ” && $textcolor != ”) {
$out .= ‘ style=”color:’ . $textcolor . ‘;”‘;
}

if ($target == ‘_blank’) {
$out .= ‘ target=”‘ . $target . ‘”‘;
}

if ($lightbox == ‘true’) {
$out .= ‘ rel=”lightbox”‘;
}

if ($tooltip != ”) {
$out .= ‘ title=”‘ . $tooltip . ‘”‘;
}

$out .= ‘ alt=”‘;
$out .= do_shortcode($content);
$out .= ‘”>’;

$out .= ‘<span>’;
$out .= do_shortcode($content);
$out .= ‘</span>’;

$out .= ‘</a>’;

return $out;
}
add_shortcode(‘button’, ‘brtheme_button’);

So, your final shortcode is:

​Leave a Comment

Comment authors age:




How to do Business Marketing by Facebook

How to Create Custom Post Type in WordPress