函数文档

wp_sprintf_l()

💡 云策文档标注

概述

wp_sprintf_l() 是一个 WordPress 函数,用于本地化列表项并将其插入到内容开头。它通过 '%l' 占位符处理数组参数,根据列表项数量自动添加逗号、'and' 等分隔符,支持国际化翻译。

关键要点

  • 函数 wp_sprintf_l() 接受两个参数:$pattern(必须以 '%l' 开头)和 $args(列表项数组)。
  • 如果 $pattern 不以 '%l' 开头或 $args 为空,函数会直接返回 $pattern 或空字符串。
  • 使用 apply_filters('wp_sprintf_l', $delimiters) 钩子可以过滤翻译后的分隔符数组,支持自定义本地化格式。
  • 函数根据 $args 中列表项的数量,智能应用 'between'、'between_last_two' 和 'between_only_two' 分隔符来构建输出字符串。
  • 输出结果是将本地化列表项与 $pattern 中 '%l' 之后的内容拼接而成的字符串。

代码示例

wp_sprintf_l( __( 'My numbers: %l' ), array( 1, 2, 3, 4, 5 ) );
// 返回:My numbers: 1, 2, 3, 4, and 5

📄 原文内容

Localizes list items before the rest of the content.

Description

The ‘%l’ must be at the first characters can then contain the rest of the content. The list items will have ‘, ‘, ‘, and’, and ‘ and ‘ added depending on the amount of list items in the $args parameter.

Parameters

$patternstringrequired
Content containing '%l' at the beginning.
$argsarrayrequired
List items to prepend to the content and replace '%l'.

Return

string Localized list items and rest of the content.

Source

function wp_sprintf_l( $pattern, $args ) {
	// Not a match.
	if ( ! str_starts_with( $pattern, '%l' ) ) {
		return $pattern;
	}

	// Nothing to work with.
	if ( empty( $args ) ) {
		return '';
	}

	/**
	 * Filters the translated delimiters used by wp_sprintf_l().
	 * Placeholders (%s) are included to assist translators and then
	 * removed before the array of strings reaches the filter.
	 *
	 * Please note: Ampersands and entities should be avoided here.
	 *
	 * @since 2.5.0
	 *
	 * @param array $delimiters An array of translated delimiters.
	 */
	$l = apply_filters(
		'wp_sprintf_l',
		array(
			/* translators: Used to join items in a list with more than 2 items. */
			'between'          => sprintf( __( '%1$s, %2$s' ), '', '' ),
			/* translators: Used to join last two items in a list with more than 2 times. */
			'between_last_two' => sprintf( __( '%1$s, and %2$s' ), '', '' ),
			/* translators: Used to join items in a list with only 2 items. */
			'between_only_two' => sprintf( __( '%1$s and %2$s' ), '', '' ),
		)
	);

	$args   = (array) $args;
	$result = array_shift( $args );
	if ( 1 === count( $args ) ) {
		$result .= $l['between_only_two'] . array_shift( $args );
	}

	// Loop when more than two args.
	$i = count( $args );
	while ( $i ) {
		$arg = array_shift( $args );
		--$i;
		if ( 0 === $i ) {
			$result .= $l['between_last_two'] . $arg;
		} else {
			$result .= $l['between'] . $arg;
		}
	}

	return $result . substr( $pattern, 2 );
}

Hooks

apply_filters( ‘wp_sprintf_l’, array $delimiters )

Filters the translated delimiters used by wp_sprintf_l() .

Changelog

Version Description
2.5.0 Introduced.

User Contributed Notes