Shortcodes was first introduced in WordPress 2.5. Many of WordPress plugins and Themes provides shortcodes for adding some functionality directly in posts and pages.

Advertisement

Create Simple ShortCode

A simple shortcode is looks like [shortcode_name] , behind which a block of code is written inside a function. Every time we use shortcode the function executed and return its values back. Remember that we use return to return values from function. All this value in functions.php.

function shortcode_function() {
  return 'Values to return';
}

Now we need to register a shortcode with add_shortcode function, which will execute this function on each call. It takes two arguments: first is shortcode name and second is function which will be execute on call.

add_shortcode('shortcode_name', 'shortcode_function');

Now we can place shortcode anywhere in posts or pages and it will display the return values from defined function.

[shortcode_name]

Example Simple ShortCode

Below is the simple example of shortcode which will display company name when ever we use shortcode. Edit your themes functions.php file and add following code.


function showCompanyName() {
  return 'TecAdmin InfoSolution Pvt Ltd';

}
add_shortcode('cname', 'showCompanyName');

Now add following shortcode in your WordPress posts of pages.

[cname]
Share.
Leave A Reply


Exit mobile version