使用短代码有两种场景:

  • 短代码是一个自闭合标签,就像我们在基础短代码部分中看到的。
  • 短代码包围内容。

包围内容

使用短代码包围内容允许对包围的内容进行操作。

[wporg]要操作的内容[/wporg]

如上所示,为了包围一段内容,您只需添加一个起始 [$tag] 和一个结束 [/$tag],类似于 HTML。

处理被包围的内容

让我们回到我们原始的 [wporg] 短代码:

function wporg_shortcode( $atts = array(), $content = null ) {
    // do something to $content
    // always return
    return $content;
}
add_shortcode( 'wporg', 'wporg_shortcode' );

查看回调函数,我们看到我们选择接受两个参数,$atts 和 $content。$content 参数将包含我们的包围内容。我们将在后面讨论 $atts。

$content 的默认值设置为 null,因此我们可以使用 PHP 函数 is_null() 来区分自闭合标签和包围标签。

短代码 [$tag](包括其内容和结束 [/$tag])将被替换为处理函数的返回值。

处理函数有责任确保输出安全。

短代码嵌套

短代码解析器对帖子内容执行单次遍历。

这意味着如果短代码处理程序的 $content 参数包含另一个短代码,它不会被解析。在此示例中,[shortcode] 将不会被处理:

[wporg]另一个 [shortcode] 被包含[/wporg]

可以通过在短代码内部使用其他短代码来实现,方法是调用 do_shortcode() 于处理函数的最终返回值。

function wporg_shortcode( $atts = array(), $content = null ) {
	// do something to $content
	// run shortcode parser recursively
	$content = do_shortcode( $content );
	// always return
	return $content;
}
add_shortcode( 'wporg', 'wporg_shortcode' );

限制

短代码解析器无法处理同一 [$tag] 的包围和非包围形式的混合。

[wporg] 非包围内容 [wporg]包围内容[/wporg]

而不是被视为由文本“non-enclosed content”分隔的两个短代码,解析器将其视为一个包围“non-enclosed content [wporg]enclosed content”的单个短代码。