How to create a custom shortcode in WordPress
WordPress shortcode is the thing that is written in [ ] (Square brackets). It means anything you write in [ ] is called a shortcode and WordPress will replace that shortcode with appropriate content, which we code in our file. Let’s see How to Create a custom Shortcode in WordPress?
Shortcodes are very helpful when you want to show the same things in more places. You can use it anywhere on the site like pages, posts, and widgets.
WordPress has a default function add_shortcode() which will add a new shortcode. See the below code example.
Table of Contents
Shortcode with only name
<?php
add_shortcode( 'year', 'blogex_get_current_year' );
function blogex_get_current_year(){
// Get current date.
$current_date = date( 'Y' );
return $current_date;
}
The function add_shortcode()
has two parameters. First is the shortcode name whatever we want to keep and the second one is a callable function, which is the actual implementation of your shortcode. So when you add that shortcode in post content or in the theme, it will be replaced with the dynamic content that you have written in the function and will show in the front end.
The above code is a shortcode for getting the current year.
If you are adding the shortcode in Gutenberg then there is a shortcode block you can use by typing /shortcode
, and add [year]
.
And if you are adding the shortcode in the file then you have to use do_shortcode()
function. See the below code.
<?php echo do_shortcode( '[year]' ); ?>
Shortcode with attributes
When you want to add some values from the shortcode to your dynamic content which the shortcode fetches. You can do it with the shortcode attribute thing. See the below code.
<?php
add_shortcode( 'greet', 'blogex_greet_user' );
function blogex_greet_user( $atts ) {
$name = ! empty( $atts['name'] ) ? $atts['name'] : '';
$greet = "Hello {$name}, Welcome to BlogEx.";
return $greet;
}
Here we have managed one attribute name
in the shortcode. So you need to add the shortcode [greet name="Jon"]
and you will find the output of the shortcode Hello Jon, Welcome to BlogEx.
Must Read: