In the previous article, we printed a "Hello, World" on screen. It works, but it is clunky, ugly-looking. That's not how plugins output to pages.
The most common way plugins interact with pages, printing content on them, is through shortcodes
.
Shortcodes are small bits of text that we write in articles. They are enclosed by brackets []
, for example, [hello]
.
When WordPress renders the article, it replaces the shortcodes with plugin's output, for example, "Hello, World!"
.
Shortcodes are powerful because they extend the editor. With them, your content is not limited to Gutemberg's blocks. You can create a plugin to add a calendar to pages, or add forms, and much more.
Let's create a "Hello, World!" shortcode.
[hello]
add_shortcode( 'hello', 'hello_callback' );
function hello_callback( $atts ) {
return "<span>Hello, World!</span>";
}
[hello color="blue"]
add_shortcode( 'hello', 'hello_callback' );
function hello_callback( $atts ) {
$color = $atts['color'];
return "<span style='color: $color;'>Hello, World!</span>";
}
Set default attributes with shortcode_atts(...)
:
add_shortcode( 'hello', 'hello_callback' );
function hello_callback( $atts ) {
/** Default values. */
$attributes = shortcode_atts( [
'color' => 'black'
], $atts );
/** Print "Hello". */
$color = $attributes['color'];
return "<span style='color: $color;'>Hello, World!</span>";
}
esc_attr(...)
add_shortcode( 'hello', 'hello_callback' );
function hello_callback( $atts ) {
/** Default values. */
$attributes = shortcode_atts( [
'color' => 'black'
], $atts );
/** Print "Hello". */
$color = esc_attr( $attributes['color'] );
return "<span style='color: $color;'>Hello, World!</span>";
}
[hello]World[/hello]
The content is the second argument:
add_shortcode( 'hello', 'hello_callback' );
function hello_callback( $atts, $contents = null ) {
/** Default attributes. */
$attributes = shortcode_atts( [
'color' => 'black'
], $atts );
/** Print "Hello". */
$color = esc_attr( $attributes['color'] );
return "<span style='color: $color;'>Hello, ". esc_html( $contents )."!</span>";
}
Use esc_html(...)
to escape HTML content.
You can re-use the same callback for multiple tags. In this case, use the third argument $tag
to differentiate tags.
Let's implement two tags, [hello]
and [world]
, on a single callback:
add_shortcode( 'hello', 'hello_callback' );
add_shortcode( 'world', 'hello_callback' );
function hello_callback( $atts, $contents = null, $tag ) {
if ( 'hello' === $tag ) {
return "<span>Hello</span>";
}
return "<span>World</span>";
}