跳转到主要内容

带参数的简码

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

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


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

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

  • $atts– 数组 – [$tag] 属性
  • $content– 字符串 – 短代码中的内容。在上面的示例中,它将是“享受 WordPress.org 短代码的乐趣”。
  • $tag– string – [$tag] 的名称(即短代码的名称)

function wporg_shortcode( $atts = array(), $content = null, $tag = '' ) {}

解析属性

对于用户来说,短代码只是帖子内容中带有方括号的字符串。用户不知道哪些属性可用以及幕后发生了什么。

对于插件开发人员来说,无法强制执行属性使用策略。用户可以包括一个属性、两个属性或根本没有属性。

要控制短代码的使用方式:

完整示例

使用基本的短代码结构的完整示例,处理自关闭和封闭场景并保护输出。

一个[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' );