带参数的简码

现在我们知道了如何创建一个基本的简码以及如何将其用作自封闭和封闭的,我们将看看在简码[$tag]和处理函数中使用参数。

简码[$tag]可以接受参数,称为属性:

[wporg title="WordPress.org"]
Having fun with WordPress.org shortcodes.
[/wporg]

简码处理函数可以接受 3 个参数:

  • $atts– 数组 – [$tag] 属性
  • $content– string – 简码中的内容。在上面的示例中,它将是“享受 WordPress.org 简码带来的乐趣”。
  • $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' );