WordPress Shortcode
A Shortcode in WordPress is a simple, bracket-enclosed tag used within posts, pages, or widgets to quickly insert dynamic content or complex functionality without writing extensive code.
Why Use Shortcodes?
Shortcodes simplify content management by allowing users to insert:
- Forms (contact, subscription, registration)
- Galleries and sliders
- Buttons or CTA elements
- Embedded media or widgets
- Custom content from plugins or themes
Shortcode Syntax
A shortcode is defined with brackets:
[shortcode_name attr="value"]
shortcode_name
: Unique identifierattr
: Optional attributes to customize the output
Creating a Custom Shortcode
Example: Create a shortcode [greeting name="John"]
function greeting_shortcode( $atts ) {
$atts = shortcode_atts( [ 'name' => 'Visitor' ], $atts );
return 'Hello, ' . esc_html($atts['name']) . '!';
}
add_shortcode( 'greeting', 'greeting_shortcode' );
Usage:
[greeting name="Sarah"]
Output:
Hello, Sarah!
Where to Use Shortcodes?
- Post or page editor (classic or block editor)
- Text widgets or widget areas
- Custom fields (with
do_shortcode()
) - Template files via:
echo do_shortcode('[shortcode_name]');
Limitations & Best Practices
- Avoid overly complex logic; keep shortcodes simple
- Shortcodes are parsed after content is retrieved from the database
- Always sanitize shortcode output for security