WordPress Plugin Development Tutorial Manual - Shortcodes
As a security precaution, PHP code is prohibited within WordPress content, and in order to allow us to add content dynamically, the concept of shortcodes was introduced in WordPress 2.5.
Simple code is the code used to add content dynamically, using simple code, we can dynamically create photo albums, play videos, insert forms or implement more customized operations in the article.
Why use shortcodes?
Shortcodes are a better way to keep the content clean and semantic. Using shortcodes, we can present dynamic content to users without inserting PHP code.
When an end user adds an album to a post using a shortcode, they can set how the album is displayed using very few parameters.
Advantages of the short code:
- No HTML markup is added to the content, which means that markup and styles generated by the shortcode can be easily modified and maintained later.
- The shortcode can also accept parameters, allowing the user to modify the display of the shortcode content by adjusting the shortcode parameters as needed.
built-in shortcode
By default, WordPress includes the following shortcodes:
- caption - a shortcode to add a caption to an image or video
- gallery - shortcode for displaying albums
- audio - shortcode for embedding and playing audio files
- video - shortcode for embedding and playing video files
- playlist - show shortcodes of audio or video files
- embed - shortcode for displaying embedded content
shortcode best practice
Best practices for developing shortcodes include Plugin Development Best Practices and a few suggestions below:
- Always return! Shortcodes are actually filters, so creating "side effects" will result in unexpected errors.
- Add your own prefix in front of the shortcode to avoid conflicts with other shortcodes.
- Sterilize input and escape output
- I provide my users with clear documentation of all shortcode attributes
External resources
basic shortcode
Add basic shortcode
We can add our own shortcodes using the WordPress Shortcode API, the whole process is very simple using the add_shortcode() The function registers a callback function containing the custom input and that's it.
<?php add_shortcode( string $tag, callable $func callable $func );
Registering shortcodes in themes
<?php function wporg_shortcode($atts = [], $content = null) { // do something to $content // always return return $content; } add_shortcode('wporg', 'wporg_shortcode');
wporg is our registered shortcode, using this shortcode will call the wporg_shortcode function to display the content.
Register the shortcode in the plugin
Unlike registering a shortcode in a theme, WordPress plugins run very early in the WordPress loading process, so we need to delay the action of adding a shortcode until after WordPress initialization is complete. It is recommended to use the init
Action to realize.
<?php function wporg_shortcodes_init() { function wporg_shortcode($atts = [], $content = null) { // do something to $content // always return return $content; } } add_shortcode('wporg', 'wporg_shortcode'); } } add_action('init', 'wporg_shortcodes_init'); }
Delete shortcode
If we no longer need a shortcode, we can use the remove_shortcode() to delete.
<?php remove_shortcode( string $tag );
Make sure that we have registered the shortcode before attempting to remove it, set a higher priority for the add shortcode operation, or mount the remove shortcode operation on top of a hook that runs a little later.
Check if the shortcode exists
If you need to check if the shortcode has been registered, use the shortcode_exists() function to check.
closed shortcode
There are two forms of shortcodes in WordPress:
- Self-enclosing shortcodes, as we demonstrated in the basic shortcode, are similar to HTML tags like br and img that don't require closure tags.
- Closed shortcodes, similar to divs and p's in HTML, which need to be closed.
Contents
Using a closed shortcode allows you to manipulate the content contained in the shortcode.
[wporg] content to manipulate [/wporg]
As shown in the shortcode above, in order to include a paragraph, we need to add a start tag [$tag]
and end marker [/$tag]
The
Handling of inclusions
Let's take a look at the original [wporg] shortcode code:
<?php function wporg_shortcode($atts = [], $content = null) { // do something to $content // always return return $content; } add_shortcode('wporg', 'wporg_shortcode');
We can see that the shortcode function accepts two arguments, the$atts
respond in singing $content
(math.) genus$content
parameter holds what the closed shortcode contains.$atts
parameter holds the parameters of the shortcode, which we describe in detail in the next section.
$content
defaults to null, we can use the PHP function is_null() to distinguish between closed and self-closed tags.
When the shortcode is displayed, the shortcode [$tag]
The content and end tags contained therein [/$tag]
The callback function that will be shortcoded by thereturn valueReplacement.
[c-alert type="warning" content="Please be aware of the safe output issue with shortcode callbacks." /]
shortcode nesting
The shortcode parser only passes the contents of the shortcode once. This means that if $content contains another shortcode, the shortcode it contains will not be parsed. As follows:
[wporg]another [shortcode] is included[/wporg]
We can call the final return value of the handler function on the do_shortcode() so that the shortcodes contained in $content can also be parsed.
<?php function wporg_shortcode($atts = [], $content = null) { // do something to $content // run shortcode parser recursively $content = do_shortcode($content); // always return return $content; } } add_shortcode('wporg', 'wporg_shortcode');
limitation
The shortcode parser cannot handle mixed closed and self-closed shortcodes, as follows:
[wporg] non-enclosed content [wporg] enclosed content[/wporg]
non-enclosed content
The parser doesn't treat it as consisting of text "[wporg]
" separated by two short codes, but instead treat it as a code containing " non-enclosed content [wporg] enclosed content
"Short code.
Short code with parameters
Now that we know how to create a basic shortcode and how to create self-closing and closing shortcodes, let's now learn about shortcodes if they handle parameters.
The shortcode can accept a number of parameters, which we call properties of the shortcode:
[wporg title="WordPress.org"] Having fun with WordPress.org shortcodes. [/wporg]
The shortcode handler can take 3 parameters:
$atts
- Arrays - properties of [$tag$content
- String - what the shortcode contains$tag
- String - Name of [$tag] (i.e., the name of the shortcode)
function wporg_shortcode($atts = [], $content = null, $tag = '') {}
Parsing Properties
To the user, shortcodes are just strings with square brackets in the article, and it is impossible for the user to know what attributes the shortcode contains and what those attributes do.
For plugin developers, we force the user to use attributes, and the user can use an attribute or not use it at all.
In order to control how the shortcode is used, we need to accomplish the following:
- Declare the default parameters of the handler function
- utilization array_change_key_case() function normalizes the key size of the attribute array
- utilization shortcode_atts() Provide an array of default values and parse user attributes
$atts
- Before returningSecuring the output
Full Example
Below is a complete example of a shortcode that uses the basic shortcode structure, takes care of self-enclosures and closures, and takes care of sanitizing and escaping the attributes and output of the shortcode. The [wporg] shortcode below accepts a title parameter and shows us a text box that can be beautified with CSS.
<?php function wporg_shortcode($atts = [], $content = null, $tag = '') { // normalize attribute keys, lowercase $atts = array_change_key_case((array)$atts, CASE_LOWER); // override default attributes with user attributes $wporg_atts = shortcode_atts([ 'title' => 'WordPress.org'. ], $atts, $tag). // start output $o = ''; // start box $o . = '<div class="wporg-box">'; // title $o . = '<h2>' . esc_html__($wporg_atts['title'], 'wporg') . '</h2>'; // enclosing tags if (!is_null($content)) { // secure output by executing the_content filter hook on $content $o . = apply_filters('the_content', $content); // run shortcode parser recursively $o . = do_shortcode($content); } // end box $o . = '</div>'; // return output return $o; } } function wporg_shortcodes_init() { add_shortcode('wporg', 'wporg_shortcode'); } function wporg_shortcode_init(); } } add_action('init', 'wporg_shortcodes_init'); }
TinyMCE Enhanced Shortcodes
We can parse the shortcodes in the TinyMCE visual editor and have them display the actual content, not the shortcodes themselves.
Switching to "Text" mode, we can see the actual shortcode.
Below is the shortcode for the TinyMCE enhancements built into WordPress.
audio shortcode
Using the audio shortcode, we can embed an audio file.
shortcode
caption
Wrap the content inside a div, and then add the <p class="wp-caption-text">
A description of the content is displayed inside the label.
Album shortcodes
The gallery shortcode allows us to embed multiple images inside a div at the same time, and the images can be arranged in columns.
playlist shortcode
The playlist shortcode allows us to add multiple media files and display them as an HTML5 playlist.
shortcode
The video shortcode video is very similar to the audio shortcode audio, except that it is displayed as a video.