How to make Shortcode in WordPress? Simple and Easy

how_to_create_a_shortcode_in_wordpress

WordPress offers a great way to extend functionality of website. One of the most easy and most used way is to build shortcodes for common functions and other great benefits. Usually it looks creating shortcodes requires quite long coding and time. But it’s not so and you can easily create shortcode for your website or plugin.

What is Shortcode?

Did you ever see a text within brackets in WordPress? Then you have already seen a short code. Shortcodes  are:

bits of small code that allow WordPress website users to do various things very easily. Without writing any script.”

Shortcode looks like this:

[Active24-shortcode].

You can enter the special tags in several places on WordPress. It replaces the content, when a web visitor views its WordPress site with code that shortcode return function runs at backend.

Creating a simple Shortcode with no arguements

Let’s create a simple shortcode that returns current date and time

add_shortcode('current_time','call_time_function');
function call_time_function(){
$currenttime= date('d M Y h:i:s');
return $currenttime;
}

In above code we create shortcode [current_time] which calls function call_time_function which returns current time using PHP date() function. Now when user will write shortcode [current_time], It will display current time to user.

Advanced Shortcode with arguements

Let’s create a shortcode that uses arguments and thus provide more flexibility to developers. Here is simple example. We will use shortcode to display favourite color of student using arguements. If no argument is used than we will use default arguments.

add_shortcode('student_fav_color','function_favcolor');

function functiom_favcolor($atts){
 extract(shortcode_atts(array(
      'color' => 'red',
   ), $atts)); //Extract Shortcodes
$colorhtml="Student Fav Color is ".$colorhtml;
return $colorhtml;
} 

Here we can use shortcode [student_fav_color] with argument color like [student_fav_color color=brown] will return “Student Fav Color is brown”. If no argument is passed it will use default value red and return “Student Fav Color is red”.

Conclusion

Hope the above code make you understand shortcodes concept easily. Incase if you have some doubt please let me know in comments.