A shortcode are a great customizable feature of WordPress that is basically a placeholder for other content.
When implemented on the Dashboard side in the WYSIWYG editor, it will look like:
[newsletter title="this is a different title"]
And perhaps appear something like:
My example here is a shortcode where a newsletter signup can be placed within a post or page’s content. It has a default attribute set for the title but if the user wants it to have a different title, they can add different content. For brevity’s sake in this case, newsletter()
hypothetically drop in the markup for the signup fields.
Shortcode Snippet
function newsletter_shortcode( $passed_values ) {
$attributes = shortcode_atts( array(
'title' => 'I\'d love to write to you',
), $passed_values );
return "<div class='newsletter'><h3>" . $attributes['title'] . '</h3>' . newsletter() . '</div>';
}
add_shortcode( 'newsletter', 'newsletter_shortcode' );
Parameters:
The add_shortcode
function requires two parameters, both of which are under our control.
'newsletter'
: What you want to name your shortcode and utilize between square brackets in the WordPress WYSIWYG where you want the markup to appear.''newsletter_shortcode''
:The name of the function which handles the output.
Shortcode Usage:
If you wanted to utilize the shortcode but not pass in a different title, you would use the more pared down version without passing the attribute (because we have a ‘backup’ set):
[newsletter]
Which would perhaps appear something like:
Additional Reading:
- WordPress Codex: Shortcode API
- WordPress Codex: add_shortcode