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
- In your theme's
functions.php
:
add_action('init', 'register_my_shortcodes');
function register_my_shortcodes() {
// Place your shortcode functions here
}
- 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:
- Shortcodes Ultimate - https://wordpress.org/plugins/shortcodes-ultimate/
- 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.