现在我们知道了如何创建基本短码,以及如何将其用作自闭合和封闭,我们将研究如何在短码[$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'], 'wporg' ) . '</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' );