既然我们已经了解了如何创建基本短代码以及如何将其用作自闭合和包含式,接下来我们将探讨在短代码 [$tag] 和处理函数中使用参数。
短代码 [$tag] 可以接受参数,这些参数被称为属性:
[wporg title="WordPress.org"]
Having fun with WordPress.org shortcodes.
[/wporg]短代码处理函数可以接受 3 个参数:
$atts– array – [$tag] 属性$content– string – 您的短代码内部的内容。在上面的示例中,它将是“Having fun with WordPress.org shortcodes。”$tag– string – [$tag] 的名称(即短代码的名称)
function wporg_shortcode( $atts = array(), $content = null, $tag = '' ) {}解析属性
对于用户来说,短代码只是帖子内容中包含方括号的字符串。用户不知道有哪些可用属性以及幕后发生了什么。
对于插件开发者来说,无法强制规定属性的使用策略。用户可能包含一个属性、两个或根本没有。
为了控制短代码的使用方式:
- 声明处理函数的默认参数
- 使用 array_change_key_case() 对属性的键大小写进行规范化
- 使用 shortcode_atts() 解析属性,提供默认值数组和用户
$atts - 在返回之前确保输出安全
完整示例
使用基本短代码结构的完整示例,处理自闭合和包含式场景并确保输出安全。
一个 [wporg] 短代码,它将接受标题并显示一个我们可以用 CSS 样式的框。
/**
* The [wporg] shortcode.
*
* Accepts a title and will display a box.
*
* @param array $atts Shortcode attributes. Default empty.
* @param string $content Shortcode content. Default null.
* @param string $tag Shortcode tag (name). Default empty.
* @return string Shortcode output.
*/
function wporg_shortcode( $atts = [], $content = null, $tag = '' ) {
// normalize attribute keys, lowercase
$atts = array_change_key_case( (array) $atts, CASE_LOWER );
// override default attributes with user attributes
$wporg_atts = shortcode_atts(
array(
'title' => 'WordPress.org',
), $atts, $tag
);
// start box
$o = '<div class="wporg-box">';
// title
$o .= '<h2>' . esc_html( $wporg_atts['title'] ) . '</h2>';
// enclosing tags
if ( ! is_null( $content ) ) {
// $content here holds everything in between the opening and the closing tags of your shortcode. eg.g [my-shortcode]content[/my-shortcode].
// Depending on what your shortcode supports, you will parse and append the content to your output in different ways.
// In this example, we just secure output by executing the_content filter hook on $content.
$o .= apply_filters( 'the_content', $content );
}
// end box
$o .= '</div>';
// return output
return $o;
}
/**
* Central location to create all shortcodes.
*/
function wporg_shortcodes_init() {
add_shortcode( 'wporg', 'wporg_shortcode' );
}
add_action( 'init', 'wporg_shortcodes_init' );