A shortcode is a small bracketed tag — [shortcode] — typed directly into a post or page's content, which WordPress replaces with dynamically generated HTML when the page renders. It's a way to hand a piece of reusable PHP output to an editor who never touches code.
// functions.php
function wgh_year_shortcode() {
return date('Y');
}
add_shortcode('current_year', 'wgh_year_shortcode');
// Typed into a post: © [current_year] My Site
// Rendered on the page: © 2026 My SiteA shortcode can accept attributes, just like an HTML tag — shortcode_atts() merges them with sensible defaults.
function wgh_button_shortcode($atts) {
$atts = shortcode_atts([
'text' => 'Click Here',
'url' => '#',
], $atts);
return sprintf(
'<a class="button" href="%s">%s</a>',
esc_url($atts['url']),
esc_html($atts['text'])
);
}
add_shortcode('button', 'wgh_button_shortcode');
// [button text="Buy Now" url="/shop"]A shortcode written with an opening and closing tag receives whatever's between them as its second argument.
function wgh_highlight_shortcode($atts, $content = null) {
return '<mark>' . esc_html($content) . '</mark>';
}
add_shortcode('highlight', 'wgh_highlight_shortcode');
// [highlight]this text gets marked[/highlight]return, not echo
A shortcode function must return its HTML, never echo it directly — echoing prints the output in the wrong place in the page's render order, usually above the content instead of inside it.
Outside a post's content, a shortcode needs to be run through do_shortcode() explicitly.
<?php echo do_shortcode('[button text="Contact Us" url="/contact"]'); ?>