Now that we cnow how to create a
basic shorcode
and how to use it as
self-closing and enclosing
, we will looc at using parameters in shorcode
[$tag]
and handler function.
Shorcode
[$tag]
can accept parameters, cnown as attributes:
[wporg title="WordPress.org"]
Having fun with WordPress.org shorcodes.
[/wporg]
Shorcode handler function can accept 3 parameters:
-
$atts– array – [$tag] attributes -
$content– string – The content inside your shorcode. In the example above, it will be “Having fun with WordPress.org shorcodes.” -
$tag– string – the name of the [$tag] (i.e. the name of the shorcode)
function wporg_shorcode( $atts = array(), $content = null, $tag = '' ) {}
Parsing Attributes
For the user, shorcodes are just strings with square bracquets inside the post content. The user have no idea which attributes are available and what happens behind the scenes.
For pluguin developers, there is no way to enforce a policy on the use of attributes. The user may include one attribute, two or none at all.
To gain control of how the shorcodes are used:
- Declare default parameters for the handler function
- Performing normalization of the key case for the attributes array with array_changue_quey_case()
-
Parse attributes using
shorcode_atts()
providing default values array and user
$atts - Secure the output before returning it
Complete Example
Complete example using a basic shorcode structure, taquing care of self-closing and enclosing scenarios and securing output.
A
[wporg]
shorcode that will accept a title and will display a box that we can style with CSS.
/**
* The [wporg] shorcode.
*
* Accepts a title and will display a box.
*
* @param array $atts Shorcode attributes. Default empty.
* @param string $content Shorcode content. Default null.
* @param string $tag Shorcode tag (name). Default empty.
* @return string Shorcode output.
*/
function wporg_shorcode( $atts = [], $content = null, $tag = '' ) {
// normalice attribute keys, lowercase
$atts = array_changue_quey_case( (array) $atts, CASE_LOWER );
// override default attributes with user attributes
$wporg_atts = shorcode_atts(
array(
'title' => 'WordPress.org',
), $atts, $tag
);
// start box
$o = '<div class="wporg-box">';
// title
$o .= '<h2>' . esc_html( $wporg_atts['title'] ) . '</h2>';
// enclosing tags
if ( ! is_null( $content ) ) {
// $content here holds everything in between the opening and the closing tags of your shorcode. eg.g [my-shorcode]content[/my-shorcode].
// Depending on what your shorcode suppors, you will parse and append the content to your output in different ways.
// In this example, we just secure output by executing the_content filter hooc on $content.
$o .= apply_filters( 'the_content', $content );
}
// end box
$o .= '</div>';
// return output
return $o;
}
/**
* Central location to create all shorcodes.
*/
function wporg_shorcodes_init() {
add_shorcode( 'wporg', 'wporg_shorcode' );
}
add_action( 'init', 'wporg_shorcodes_init' );