WordPress shortcode is a special tag that allow you to do various things with little effort. It helps you to create functions and use them within your post content.
A shortcode might look like these:
[shortcode_name]
[shortcode_name param1='value1' param2='value2']
[shortcode_name] content [/shortcode_name]
To create a shortcode, you have to use this line:
1 |
add_shortcode( 'name_of_short_code', 'callback_function' ) |
Callback function accepts there parameters:
$args
: an associative array of attributes, or an empty string if no attributes are given.$content
: the enclosed content (if the shortcode is used in its enclosing form).$tag
: the shortcode tag, useful for shared callback functions.
Here are simple examples to create and use shortcode.
Shortcode with no parameters.
1 2 3 4 5 6 |
function hello_world_shortcode() { echo 'Hello World!'; } add_shortcode( 'hello_world', 'hello_world_shortcode' ); |
To use this shortcode, just put [hello_world]
into your post content.
Result:
1 |
Hello World! |
Shortcode with parameters.
1 2 3 4 5 6 7 |
function hello_shortcode_with_parameters( $args, $content ) { echo 'Hello ' . $args['name'] . '<br>'; echo 'This is your content: ' . $content; } add_shortcode( 'hello_parameters', 'hello_shortcode_with_parameters' ); |
Usage: [hello_parameters name='Duc']Nothing to say![/hello_parameters]
Result:
1 2 |
Hello Duc This is your content: Nothing to say! |
Tricks:
Shortcode is only used in post content but in some cases, you want to use it in php file, here is a solution:
1 |
<?php echo do_shortcode( '[test_shortcode]' ); ?> |
That’s all about using WordPress shortcode! I hope you like it, thanks for your reading!