LESSON 04 / 04

Shortcodes

Let writers drop dynamic content into posts with [shortcodes] — with attributes, defaults and enclosed content.

🎓Mediumlevel
⏱️30 minto finish
✏️2activities

📂 Plugins & Hooks🏷️ WordPress

🎯 By the end of this lesson you can…

  • Register a shortcode
  • Handle attributes with shortcode_atts
  • Return (not echo) escaped HTML
🔌 WordPress PHP shortcode.php 👆 Tap a line to explain it
1<?php2add_shortcode( 'badge', function ( $atts, $content = '' ) {3    $a = shortcode_atts( [ 'color' => 'purple', 'icon' => '⭐' ], $atts );4    return sprintf(5        '<span class="badge" style="background:%s">%s %s</span>',6        esc_attr( $a['color'] ),7        esc_html( $a['icon'] ),8        esc_html( $content )9    );10} );11 12echo do_shortcode( 'Well done! [badge color="green" icon="🏆"]Champion[/badge]' ), "\n";13echo do_shortcode( '[badge]Default[/badge]' ), "\n";
🛠️ Countdown shortcode

Register [days_until date="2026-12-25"] that returns N days to go (days from 2026-09-27, the fixed “today” for the test), or Today! when N is 0.

Shortcodes inside shortcodes

Content between the opening and closing tags is passed to your callback as $content, but shortcodes inside it are not run automatically. Call do_shortcode( $content ) to allow nesting.

🔌 WordPress PHP notice.php 👆 Tap a line to explain it
1<?php2add_shortcode( 'notice', function ( $atts, $content = '' ) {3    $a     = shortcode_atts( [ 'type' => 'info' ], $atts, 'notice' );4    $icons = [ 'info' => 'ℹ️', 'tip' => '💡', 'warning' => '⚠️' ];5    $icon  = $icons[ $a['type'] ] ?? $icons['info'];6    return '<div class="notice notice--' . esc_attr( $a['type'] ) . '">' . $icon . ' ' . do_shortcode( $content ) . '</div>';7} );8add_shortcode( 'year', fn() => '2026' );9 10echo do_shortcode( '[notice type="tip"]Copyright [year] — keep learning![/notice]' ), "\n";11echo do_shortcode( '[notice type="nope"]Unknown types fall back to info.[/notice]' ), "\n";
🐞 Find the error
This shortcode’s text appears at the very top of the post, not where [hello] was typed. Why?
1add_shortcode( 'hello', function () {2    echo 'Hello!';3} );

📌 Key takeaways

  • add_shortcode( 'tag', $callback ) — the callback returns HTML.
  • shortcode_atts( $defaults, $atts ) fills in missing attributes.
  • Escape attribute values before using them in HTML.

Finished reading & practising?

Saved in this browser. Create a free account to keep it forever.