What Are WordPress Shortcodes?
Shortcodes are small pieces of code you can insert inside posts, pages, or widgets to display dynamic content. They look like this:
[gallery ids="1,2,3"]
Instead of writing long blocks of HTML or PHP, WordPress interprets the shortcode and outputs the correct content. This makes them perfect for beginners who want functionality without writing complex code.
Types of Shortcodes
There are two main types:
- Self-closing shortcodes: Work alone.
Example:[year]
→ outputs the current year. - Enclosing shortcodes: Wrap around content.
Example:[note]This is important[/note]
Many plugins also ship with their own shortcodes—for example, a contact form plugin might provide [contact-form-7]
to display a form.
Using Shortcodes in WordPress
Adding shortcodes is simple:
- Insert them directly into your post/page editor.
- Use the Shortcode block in Gutenberg.
- Insert in widgets (like a text widget).
- Even render them in PHP templates using:
<?php echo do_shortcode('[year]'); ?>
How to Create Your Own Shortcode
You’re not limited to pre-made shortcodes—creating your own is straightforward. Just add this snippet to your child theme’s functions.php
or a custom plugin:
// Outputs the current year
add_shortcode('year', function () {
return date('Y');
});
// Custom button shortcode
add_shortcode('button', function ($atts, $content = '') {
$a = shortcode_atts([
'url' => '#',
'style' => 'primary'
], $atts);
$url = esc_url($a['url']);
$class = 'btn btn-' . sanitize_html_class($a['style']);
return '<a class="' . $class . '" href="' . $url . '">' . esc_html($content) . '</a>';
});
Now you can use:
[button url="/contact" style="secondary"]Contact Us[/button]
And it will output a styled button linking to your contact page.
Best Practices for Shortcodes
- Sanitize input: Always use
esc_url
oresc_html
for user attributes. - Keep them lightweight: Don’t overload a shortcode with heavy queries.
- Avoid name collisions: Prefix your shortcode names (e.g.,
[wpdoctor_button]
). - Prefer blocks when possible: Shortcodes are powerful, but newer Gutenberg blocks often offer a better user experience.
Common Issues & Troubleshooting
- Shortcode shows as plain text? Check if you’re using the right block or if the plugin providing the shortcode is active.
- Not rendering in widgets? Ensure the widget supports shortcodes (enable with
add_filter('widget_text', 'do_shortcode');
).
Final Thoughts
Shortcodes remain one of WordPress’s most flexible features. They give beginners power to add complex elements with a single line, while developers can extend them endlessly. Whether you’re displaying forms, galleries, or custom content, shortcodes save time and simplify workflow.
💡 Pro Tip: If you’re building multiple shortcodes, bundle them into a mini custom plugin instead of functions.php
. That way, they’ll stay portable even if you switch themes.