WordPress is a multi-purpose CMS for creating any kind of website. It is super flexible and you can create business website, blog website, personal website, portfolio, and various kind of web applications as well using it.

Shortcode is a very important and useful feature of WordPress. Using the shortcode, you can create functionalities that can be used anywhere in the website. You can use the shortcodes inside the theme files or templates, content editor of pages & posts in admin portal, in HTML widget, etc.

In this post, we will see how to create shortcode in wordpress and how you can use the shortcode within your post content or template file.

Creating shortcode in wordpress functions.php

Shortcodes are created inside the functions.php file within your theme directory. add_shortcode is the function in wordpress that registers/create/add your shortcode.

add_shortcode( $tag, $function );

$tag => this is the unique string that will be used to call the shortcode
$function => Hook function which will be executed when this shortcode is called

Custom Shortcode Create Example

Suppose, I want to display the the below based on conditions.
If value is “yes”, then shortcode should print “Yes. This is truth.”
If value is “no”, then shortcode should print “No. This is a lie.”

To do this, we will create a shortcode with name truthlie in functions.php file. We need to pass 1 argument in it i.e. answer.

// function truthlie_func
function truthlie_func( $atts ) {
  // $atts => default values if parameters are not passed
  $atts = shortcode_atts( array(
		'answer' => 'no'
	), $atts, 'truthlie' );
  print_r($atts);
}
// adding the shortcode; hooking the tag 'truthlie' with the function
add_shortcode( 'truthlie', 'truthlie_func' );

Inside the function, we have used shortcode_atts function. This function combines attributes provided by the user with the known/default values if the value is not provided.

Calling the shortcode in WordPress

Now, we have created our custom shortcode in WordPress functions.php file. It’s time to call the shortcode in content or template files.

Calling Shortcode in Page or Post content

Shortcodes are called using the square brackets as follows.

[truthlie answer="yes"]

This will interpret the shortcode and displays the appropriate result. Note that, if the shortcode is not created, then the WordPress will display the text as it is.

Calling Shortcode in template file

The template files are created using PHP. So, in order to call the shortcode in the PHP file, we use do_shortcode function.
do_shortcode function returns the result. So, we need to echo it.

<?php
  echo do_shortcode('[truthlie answer="yes"]');
?>

Yes, it’s that simple. You can use it to do so many big tasks. For example: you can create shortcodes:

  • To fetch ‘x’ latest posts
  • To implement condition based logic in post content
  • To use PHP functions type functionality inside page or post content
  •  

there is much more you can do with it…