WordPress shortcode inside and outside
First appeared on mobifreaks.com · Updated
Shortcodes are still part of WordPress, and this snippet still works. I have tidied it up and added the notes I wish I had in 2011.
Create the shortcode
It starts with a PHP function that returns the output, registered with add_shortcode(). Put it in your theme's functions.php or, better, a small plugin so it survives a theme change.
<?php
function mf_hello_shortcode( $atts ) {
$atts = shortcode_atts( array( 'name' => 'there' ), $atts, 'hello' );
return 'Hello, ' . esc_html( $atts['name'] ) . '!';
}
add_shortcode( 'hello', 'mf_hello_shortcode' );
- Always
returnthe output, neverechoit. Echoed output appears in the wrong place, usually at the top of the post. shortcode_atts()sets default values for attributes.esc_html()escapes anything a post author types into an attribute.- Prefix the function name (
mf_here) so it can't clash with another plugin.
Use it inside a post or page
[hello]
[hello name="Munawar"]
In the block editor, add a Shortcode block and type it there.
Use it outside, in theme files
Theme templates don't process shortcodes on their own, so run it through do_shortcode():
<?php echo do_shortcode( '[hello name="Munawar"]' ); ?>
If the code is yours, it is cleaner to call the function directly: echo mf_hello_shortcode( array( 'name' => 'Munawar' ) );.
Today
For anything with a visual interface, WordPress now prefers blocks, which authors can see and edit in place. Shortcodes are still fine for small dynamic snippets.
The full reference is the Shortcodes chapter of the WordPress Plugin Handbook.