使用短代码有两种情况:
- 短码是一个自闭合标签,就像我们在基本短码部分中看到的那样。
- 短代码是封闭内容。
封闭内容
用短代码封装内容允许对封装的内容进行操作。
[wporg]content to manipulate[/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],将替换为处理程序函数的返回值。
Alert:处理函数负责安全输出。
短代码异常
短码解析器对文章的内容执行一次传递。
这意味着,如果短代码处理程序的$content参数包含另一个短代码,则不会对其进行解析。在本例中,将不处理[shortcode]:
[wporg]another [shortcode] is included[/wporg]
通过对处理函数的最终返回值调用do_shortcode(),可以在其他短代码内使用短代码。
5function 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] non-enclosed content [wporg]enclosed content[/wporg]
解析器没有将其视为由文本 non-enclosed content 分隔的两个短码,而是将其视为包含 non-enclosed content [wporg]enclosed content的单个短码。