add_shortcode()
Adds a new shortcode and a hook for it.
For each shortcode, only one handler function can be created. This means that if another plugin uses the same shortcode, your function will be replaced by another one or vice versa (depending on the order in which the functions are connected).
Uses global variable global $shortcode_tags.
Be sure to read: Creating Shortcodes in WordPress
No Hooks.
Returns
null. Does not return anything.
Usage
add_shortcode( $tag, $callback );
- $tag(string) (required)
The name of the shortcode that will be used in the text. For example: 'gallery'.
In the name, spaces and non-standard characters like:
& / < > [ ] =cannot be used.- $callback(string) (required)
The name of the function that will output the shortcode content - replacing the shortcode with something.
The shortcode function must return data, not output it -
return, notecho.The function receives three parameters:
-
$atts(array)
An associative array of attributes specified in the shortcode. More about shortcode attributes.The names of the shortcode attributes are always converted to lowercase before they are passed to the handler function.
Default: '' (empty string - no attributes)
-
$content(string)
The text of the shortcode when using a content shortcode: [foo]shortcode text[/foo]
Default: '' - $tag(string)
The name of the shortcode. Passed to hooks. For example, for the shortcode[foo], the tag will befoo.
-
Examples
#1 One function for multiple shortcodes
Suppose we need to create several shortcodes of the same type, which have the same parameters allowed. It is not necessary to create a separate PHP function for each shortcode, but we can use the same function for all the shortcodes.
To understand which shortcode works inside the function, a third parameter is passed to the shortcode function, which contains the name of the current shortcode:
add_shortcode( 'baz-up', 'baz_func' );
add_shortcode( 'baz-down', 'baz_func' );
function baz_func( $atts, $content, $tag ) {
// some general logic, like processing $atts variables
$atts = shortcode_atts( array(
'foo' => 'no foo',
'baz' => 'default baz'
), $atts );
if( 'baz-up' === $tag ){
$content = 'The shortcode [baz-up] contint is ' . $atts['foo'];
}
elseif( 'baz-down' === $tag ){
$content = 'The shortcode [baz-down] contint is ' . $atts['foo'];
}
return $content;
}
#2 An example of [footag foo="bar"] shotcode registration:
add_shortcode( 'footag', 'footag_func' );
function footag_func( $atts ){
return "foo = ". $atts['foo'];
}
// Result:
// the shortcode [footag foo="bar"] will be replaced by "foo = bar" in the text #3 Registering a content-shortcode
An example of how to create such a shotcode: [baztag]here is text[/baztag]:
add_shortcode( 'baztag', 'baztag_func' );
function baztag_func( $atts, $content ) {
return "content = $content";
}
// Result:
// the shottcode construction will be replaced by "content = here text" #4 Registering a short code OOP style
If your plugin is written by a class:
add_shortcode( 'baztag', [ 'MyPlugin', 'baztag_func' ] );
class MyPlugin {
public static function baztag_func( $atts, $content ) {
return "content = $content";
}
}
OR
class MyPlugin {
public function baztag_func( $atts, $content ) {
return "content = $content";
}
}
$class = new MyPlugin();
add_shortcode( 'baztag', [ $class, 'baztag_func' ] ); #5 Inserting iframes via shortcode
This example shows how to create a shortcode to insert an iframe.
add_shortcode( 'iframe', 'Generate_iframe' );
function Generate_iframe( $atts ) {
$atts = shortcode_atts( [
'href' => 'http://example.com',
'height' => '550px',
'width' => '600px',
], $atts );
return strtr( '
<iframe src="{src}" width="{width}" height="{height}">
<p>Your Browser does not support Iframes.</p>
</iframe>',
[
'{src}' => esc_attr( $atts['href'] ),
'{width}' => esc_attr( $atts['width'] ),
'{height}' => esc_attr( $atts['height'] ),
]
);
}
// usage:
// [iframe href="http://www.exmaple.com" height="480" width="640"] #6 Connecting theme templates in the shortcode
Suppose we need to connect a specially prepared file via shortcode:
add_shortcode( '4cards', 'shortcode_4cards' );
function shortcode_4cards() {
ob_start();
/**
* Connects the file to the path:
* my_domain/wp-content/themes/my_theme/templates/shortcodes/4_cards.php
*/
get_template_part( 'templates/shortcodes/4_cards' );
return ob_get_clean();
}
// Example of a shortcode call: ``[4cards]``
Thanks to the parameters that can be passed to the shortcode, you can provide for dynamic connection of the desired file from a folder. Let's refine the example:
add_shortcode( 'cards', 'shortcode_cards' );
function shortcode_cards( $atts ) {
ob_start();
// white parameter list
$atts = shortcode_atts( [
'template' => '',
], $atts );
/**
* Connects the file to the path:
* my_domain/wp-content/themes/my_theme/templates/shortcodes/transmitted_file_name.php
*/
get_template_part( "templates/shortcodes/{$atts['template']}" );
return ob_get_clean();
}
Examples of shortcode calls:
# /theme/templates/shortcodes/card-1.php [cards template="card-1"] # /theme/templates/shortcodes/card-2.php [cards template="card-2"] # /theme/templates/shortcodes/cart-1/block-1.php [cards template="cart-1/block-1"]
#7 First callback argument is an empty string
Beware that the first argument passed to the callback is an empty string if no attributes are set in the shortcode. So a type declaration will fail:
“Fatal error: Uncaught Error: Argument 1 passed to shortcode_callback() must be of the type array, string given”
Use a check whether $arguments is not an array and if so, replace it with an empty array:
function shortcode_callback( $attributes, string $content, string $shortcode ) {
if ( ! is_array( $attributes ) ) {
$attributes = [];
}
// do stuff
} #8 Setting the white list of shortcode attributes
In order for a shortcode to have only the parameters we specified and for these parameters to have default values, you need to use the function shortcode_atts():
add_shortcode( 'bartag', 'bartag_func' );
function bartag_func( $atts ){
// white list of parameters and default values
$atts = shortcode_atts( array(
'foo' => 'no foo',
'baz' => 'default baz'
), $atts );
return "foo = {$atts['foo']}";
} #9 Display posts by ID via shortcode
Get the post by ID using the [testimonials id="272"] shortcode.
Place the following code into the theme functions.php file.
add_shortcode( 'testimonials', 'testimonials_shortcode_handler' );
function testimonials_shortcode_handler( $atts ){
global $post;
$rg = (object) shortcode_atts( [
'id' => null
], $atts );
if( ! $post = get_post( $rg->id ) )
return '';
$url = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
$out = '
<div class="testimonial">
<div class="testimonial-img">
<img src="'. $url .'" />
</div>
<div class="testimonial-content">
<img src="' . esc_attr( $post->logo ) . '" alt="icon" />
<p class="testimonial_desc">'. get_the_content() .'</p>
<div class="author-details">
<img src="' . esc_attr( $post->author_image ) .'" alt="image">
<p>
'. esc_html( $post->author_name ) .'
<span>'. esc_html( $post->author_designation ) .'</span>
</p>
</div>
</div>
</div>
';
wp_reset_postdata();
return $out;
}
Notes
- Global. Array. $shortcode_tags
Changelog
| Since 2.5.0 | Introduced. |