附上简码
使用简码有两种情况:
- 简码是一个自闭合标签,就像我们在基本简码部分看到的那样。
- 简码包含内容。
附上内容
使用简码包含内容允许对包含的内容进行操作。
[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()区分自闭合标签和封闭标签。
shortcode [$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
”的单个简码。