How to create shortcode in WordPress

WordPress shortcode will help you to call a function in your posts, page, php files. This is pretty simple to create this shortcode tag in your wordpress site.

Example for [products]

Step – 1 : At first, open the function.php file in your editor, create a function that must return data that you want to print (not echo, print etc).

function ShowProduct()
{
  $data = "Welcome to wordpress shortcode.";
  return $data;
}

Step – 2 : Now we will call the wordpress shortcode API under the function to activate our shortcode.

add_shortcode('products', 'ShowProduct');

Step – 3 : Now we can use this shortcode tag [products] in our posts,page. Also if we want to use the shortcode in our php files, use the following code

echo do_shortcode( '[products]' );

Output :
Welcome to wordpress shortcode.

Example for shortcode attributes [products number=5]

Step – 1 : Update the function like as bellow functions

function ShowProduct($atts)
{
  $number = $atts['number'];
  $data = "Number = ".$number;
  return $data;
}

Step – 2 : Add the following same code to activate the shortcode. No changes are here.

add_shortcode('products', 'ShowProduct');

Step – 3 : Now use this shortcode tag [products number=5] in our posts,page.

Output :
Number=5