附上简码
使用短代码有两种场景:
- 短代码是一个自闭合标签,就像我们在基本短代码部分中看到的那样。
- 短代码包含内容。
附上内容
使用短代码封装内容允许对封装的内容进行操作。
[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]
将替换为处理函数的返回值。
简码接收
短代码解析器对帖子的内容执行一次传递。
这意味着如果$content
短代码处理程序的参数包含另一个短代码,则不会对其进行解析。在本例中,[shortcode]
将不会被处理:
[wporg]another [shortcode] is included[/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] non-enclosed content [wporg]enclosed content[/wporg]
non-enclosed content
解析器不会将其视为由文本“”分隔的两个短代码,而是将其视为包含“ non-enclosed content [wporg]enclosed content
”的单个短代码。
无评论