Creating a Custom WordPress Shortcode
Basic Custom Shortcode Solution
Here's how to create a simple shortcode that outputs custom content. Add this code to your theme's functions.php
file or in a site-specific plugin:
Basic shortcode that outputs static content:
function my_custom_shortcode() {
$output = '<div class="custom-content">';
$output .= 'Your custom content here';
$output .= '</div>';
return $output;
}
add_shortcode('my_content', 'my_custom_shortcode');
Usage: [my_content]
Advanced Shortcode with Parameters
Shortcode that accepts parameters and returns dynamic content:
function my_advanced_shortcode($atts) {
// Set default values
$attributes = shortcode_atts(array(
'title' => 'Default Title',
'color' => 'blue',
'size' => 'medium'
), $atts);
$output = '<div class="custom-content" style="color: ' . esc_attr($attributes['color']) . ';">';
$output .= '<h2>' . esc_html($attributes['title']) . '</h2>';
$output .= '<div class="size-' . esc_attr($attributes['size']) . '">';
$output .= 'Your dynamic content here';
$output .= '</div></div>';
return $output;
}
add_shortcode('my_dynamic', 'my_advanced_shortcode');
Usage: [my_dynamic title="My Title" color="red" size="large"]
Shortcode with Content Between Tags
Shortcode that processes content between opening and closing tags:
function my_content_shortcode($atts, $content = null) {
// Process the content
$processed_content = do_shortcode($content);
$output = '<div class="wrapped-content">';
$output .= $processed_content;
$output .= '</div>';
return $output;
}
add_shortcode('wrap', 'my_content_shortcode');
Usage: [wrap]Your content here[/wrap]
Where to Place the Code
- In your theme's
functions.php
file
- In a site-specific plugin (recommended)
- Using a code snippets plugin
Plugin Solutions
If you prefer using a plugin, here are reliable options:
-
Shortcodes Ultimate - Includes 50+ ready-to-use shortcodes
-
Shortcoder - Create custom shortcodes easily through admin interface
Best Practices
- Always sanitize and escape output
- Use meaningful shortcode names
- Include default values for parameters
- Document usage for team members
- Test shortcodes thoroughly
- Use the
shortcode_atts()
function for parameters
- Return the output instead of echoing it
Tips
- Use
do_shortcode()
to process nested shortcodes
- Avoid using similar names to existing WordPress shortcodes
- Keep shortcode names lowercase and use hyphens or underscores
- Test shortcodes in both visual and text editors
This solution provides flexibility while maintaining WordPress coding standards and security practices.