The Shortcode API is basically made up of the add_shortcode()
function. It’s important to note that functions attached to shortcodes should always return output, not echo
. If you’d like to output HTML in a shortcode by escaping from PHP or using echo
/ print
, start with ob_start();
and end with return ob_get_clean();
A shortcode can be executed from PHP using the do_shortcode()
function.
Here’s an example plugin. The first function creates the shortcode, and then the second function replaces all front-end responses with shortcode’s content:
<?php
/**
* Plugin Name: Make Everything a Kitten
* Plugin Description: Add a <code>[kitten]</code> shortcode, then replace everything on the site with its content. Optional parameters are <code>width</code> and <code>height</code>. e.g., <code>[kitten width="1200" height="1200"]</code>.
*/
/**
* Register the shortcode [kitten]
* with optional attributes "width" and "height".
*/
add_shortcode(
'kitten',
function ( $a ) {
// Combine default attributes with inputted attributes.
// e.g., [kitten width="1200" height="1200"]
$a = shortcode_atts(
[
'width' => 500,
'height' => 500,
],
$a
);
ob_start();
?>
<img src="https://placekitten.com/<?php echo esc_attr( $a['width'] ); ?>/<?php echo esc_attr( $a['height'] ); ?>" />
<?php
return ob_get_clean();
}
);
/**
* Replace the entire front-end site with a kitten.
*/
add_action(
'template_redirect',
function(){
echo do_shortcode( '[kitten]' );
exit;
}
);