Developing WordPress Shortcodes
A shortcode is a WordPress mechanism that allows editors to insert arbitrary PHP output directly into post content using a command like [my_shortcode param="value"]. Editors don't need to know PHP or have access to templates—but through a shortcode they can insert a table, form, widget, or map anywhere in the content. Implementing a simple shortcode takes a few hours; a shortcode with complex rendering and settings takes 1–2 days.
Registering a Shortcode
add_shortcode('my_button', 'my_button_shortcode_handler');
function my_button_shortcode_handler(array $atts, ?string $content = null): string {
$atts = shortcode_atts([
'url' => '#',
'color' => 'primary',
'target' => '_self',
'size' => 'md',
], $atts, 'my_button');
// Sanitization
$url = esc_url($atts['url']);
$color = sanitize_html_class($atts['color']);
$target = in_array($atts['target'], ['_self', '_blank']) ? $atts['target'] : '_self';
$size = in_array($atts['size'], ['sm', 'md', 'lg']) ? $atts['size'] : 'md';
$label = $content ? wp_kses_post($content) : 'Click';
return sprintf(
'<a href="%s" target="%s" rel="%s" class="btn btn--%s btn--%s">%s</a>',
$url,
$target,
$target === '_blank' ? 'noopener noreferrer' : '',
esc_attr($color),
esc_attr($size),
$label
);
}
shortcode_atts() merges user-provided attributes with defaults. The third parameter—the shortcode name—allows filtering defaults via shortcode_atts_my_button.
Shortcode with Nested Content
add_shortcode('my_tabs', 'my_tabs_shortcode');
add_shortcode('my_tab', 'my_tab_shortcode');
function my_tabs_shortcode(array $atts, ?string $content = null): string {
if (!$content) return '';
// do_shortcode processes nested [my_tab]
$inner = do_shortcode($content);
return '<div class="my-tabs">' . $inner . '</div>';
}
function my_tab_shortcode(array $atts, ?string $content = null): string {
$atts = shortcode_atts(['title' => 'Tab', 'active' => 'no'], $atts, 'my_tab');
$is_active = $atts['active'] === 'yes' ? ' my-tab--active' : '';
$title = esc_html($atts['title']);
$body = $content ? do_shortcode($content) : '';
return "<div class=\"my-tab{$is_active}\" data-title=\"{$title}\">{$body}</div>";
}
Usage in the editor:
[my_tabs]
[my_tab title="Description" active="yes"]First tab content[/my_tab]
[my_tab title="Features"]Features list[/my_tab]
[/my_tabs]
Shortcode with Database Query
add_shortcode('recent_projects', function (array $atts): string {
$atts = shortcode_atts([
'count' => 3,
'category' => '',
'columns' => 3,
], $atts, 'recent_projects');
$args = [
'post_type' => 'project',
'posts_per_page' => absint($atts['count']),
'post_status' => 'publish',
];
if ($atts['category']) {
$args['tax_query'] = [[
'taxonomy' => 'project_category',
'field' => 'slug',
'terms' => sanitize_title($atts['category']),
]];
}
$query = new WP_Query($args);
if (!$query->have_posts()) {
return '<p>No projects found.</p>';
}
ob_start();
echo '<div class="projects-grid projects-grid--cols-' . absint($atts['columns']) . '">';
while ($query->have_posts()) {
$query->the_post();
get_template_part('template-parts/project-card');
}
wp_reset_postdata();
echo '</div>';
return ob_get_clean();
});
ob_start() / ob_get_clean() is the standard way to capture output from template parts that use echo instead of return.
Caching Results
Shortcodes with database queries or external API calls should be cached via the Transients API:
add_shortcode('exchange_rates', function (): string {
$cache_key = 'my_exchange_rates';
$cached = get_transient($cache_key);
if ($cached !== false) {
return $cached;
}
$response = wp_remote_get('https://api.exchangerate.host/latest?base=USD&symbols=EUR,GBP');
if (is_wp_error($response)) {
return '<p>Data unavailable.</p>';
}
$data = json_decode(wp_remote_retrieve_body($response), true);
$html = '<ul class="rates">';
foreach ($data['rates'] as $currency => $rate) {
$html .= "<li><strong>{$currency}:</strong> " . number_format($rate, 2) . '</li>';
}
$html .= '</ul>';
set_transient($cache_key, $html, HOUR_IN_SECONDS);
return $html;
});
TTL should be chosen based on how often data changes. For exchange rates, 1 hour is sufficient; for a visitor counter, caching is harmful.
Registering a Button in Gutenberg
To allow editors to insert a shortcode with a button rather than typing it manually, add a button to TinyMCE (classic editor) or a block wrapper for Gutenberg:
// TinyMCE plugin — adding a button to the editor
(function ($) {
tinymce.create('tinymce.plugins.my_shortcodes', {
init: function (ed) {
ed.addButton('my_button_shortcode', {
title: 'Insert button',
image: myShortcodesAdmin.pluginUrl + '/icon.svg',
onclick: function () {
const url = prompt('Button URL:');
const label = prompt('Button text:');
if (url && label) {
ed.insertContent(`[my_button url="${url}"]${label}[/my_button]`);
}
},
});
},
});
tinymce.PluginManager.add('my_shortcodes', tinymce.plugins.my_shortcodes);
})(jQuery);
Shortcodes vs Gutenberg Blocks
Shortcodes haven't become obsolete but have limitations: no preview in the editor, syntax is opaque to the editor. For new Gutenberg projects, creating custom blocks is preferable (separate service). Shortcodes remain the optimal choice for Classic Editor, Elementor, WPBakery, and any third-party builders that can process do_shortcode().







