add_shortcode()WP 2.5.0

Adds a new shortcode.

Care should be taken through prefixing or other means to ensure that the shortcode tag being added is unique and will not conflict with other, already-added shortcode tags. In the event of a duplicated tag, the tag loaded last will take precedence.

No Hooks.

Return

null. Nothing.

Usage

add_shortcode( $tag, $callback );
$tag(string) (required)
Shortcode tag to be searched in post content.
$callback(callable) (required)
The callback function to run when the shortcode is found. Every shortcode callback is passed three parameters by default, including an array of attributes ($atts), the shortcode content or null if not set ($content), and finally the shortcode tag itself ($shortcode_tag), in that order.

Examples

0

#1 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
0

#2 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;
}
0

#3 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']}";
}
0

#4 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"
0

#5 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' ] );
0

#6 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 sprintf( 
		'<iframe src="%s" width="%s" height="%s"><p>Your Browser does not support Iframes.</p></iframe>',
		$atts['href'],
		$atts['width'],
		$atts['height']
	);
}

// usage:
// [iframe href="http://www.exmaple.com" height="480" width="640"]
0

#7 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;
}
0

#8 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"]
0

#9 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
}

Notes

  • Global. Array. $shortcode_tags

Changelog

Since 2.5.0 Introduced.

add_shortcode() code WP 6.1.1

function add_shortcode( $tag, $callback ) {
	global $shortcode_tags;

	if ( '' === trim( $tag ) ) {
		_doing_it_wrong(
			__FUNCTION__,
			__( 'Invalid shortcode name: Empty name given.' ),
			'4.4.0'
		);
		return;
	}

	if ( 0 !== preg_match( '@[<>&/\[\]\x00-\x20=]@', $tag ) ) {
		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
				/* translators: 1: Shortcode name, 2: Space-separated list of reserved characters. */
				__( 'Invalid shortcode name: %1$s. Do not use spaces or reserved characters: %2$s' ),
				$tag,
				'& / < > [ ] ='
			),
			'4.4.0'
		);
		return;
	}

	$shortcode_tags[ $tag ] = $callback;
}