Adding a Custom Shortcode to WordPress

Nicolas R Dec 28, 2024 Shortcodes
How do I make a special code that shows something different on my pages when I type it?
What is the process to create a custom shortcode in WordPress using the `add_shortcode` function?
Andy answered Dec 28, 2024

Creating a Custom WordPress Shortcode

Basic Shortcode Implementation

Here's how to create a simple shortcode that displays custom content. Add this code to your theme's functions.php file or in a site-specific plugin:

Basic shortcode that returns a custom message:

function custom_message_shortcode() {
    return '<div class="custom-message">Hello, this is my custom message!</div>';
}
add_shortcode('my_message', 'custom_message_shortcode');

Use it in your posts/pages with: [my_message]

Shortcode with Attributes

Create a more flexible shortcode that accepts custom parameters:

function custom_box_shortcode($atts) {
    $attributes = shortcode_atts(array(
        'color' => 'blue',
        'title' => 'Default Title'
    ), $atts);
    
    return sprintf(
        '<div class="custom-box" style="border: 2px solid %s">
            <h3>%s</h3>
        </div>',
        esc_attr($attributes['color']),
        esc_html($attributes['title'])
    );
}
add_shortcode('custom_box', 'custom_box_shortcode');

Use it like: [custom_box color="red" title="My Title"]

Shortcode with Content

Create a shortcode that wraps around content:

function content_wrapper_shortcode($atts, $content = null) {
    $attributes = shortcode_atts(array(
        'class' => 'default-wrapper'
    ), $atts);
    
    return sprintf(
        '<div class="%s">%s</div>',
        esc_attr($attributes['class']),
        do_shortcode($content)
    );
}
add_shortcode('wrapper', 'content_wrapper_shortcode');

Use it like: [wrapper class="my-class"]Your content here[/wrapper]

Where to Place the Code

  1. In your theme's functions.php:
add_action('init', 'register_my_shortcodes');

function register_my_shortcodes() {
    // Place your shortcode functions here
}
  1. Or better, in a site-specific plugin:
<?php
/*
Plugin Name: My Custom Shortcodes
Description: Adds custom shortcodes to the site
Version: 1.0
Author: Your Name
*/

function register_my_shortcodes() {
    // Place your shortcode functions here
}
add_action('init', 'register_my_shortcodes');

Plugin Alternatives

If you prefer using plugins, here are reliable options:

  1. Shortcodes Ultimate - https://wordpress.org/plugins/shortcodes-ultimate/
  2. Shortcoder - https://wordpress.org/plugins/shortcoder/

These plugins provide user-friendly interfaces for creating and managing shortcodes without coding.

Security Notes

  • Always sanitize and escape output
  • Use wp_kses_post() for HTML content
  • Use esc_attr() for attributes
  • Use esc_html() for plain text
  • Use do_shortcode() to process nested shortcodes

Remember to clear your cache after adding new shortcodes if you're using a caching plugin.