函数文档

wp_rel_ugc()

💡 云策文档标注

概述

wp_rel_ugc() 是一个 WordPress 函数,用于在内容中的所有 HTML A 元素中添加 rel="nofollow ugc" 属性。它作为预保存过滤器运行,处理转义后的文本。

关键要点

  • 函数作用:自动为内容中的链接添加 rel="nofollow ugc" 属性,以符合用户生成内容(UGC)的 SEO 最佳实践。
  • 参数:接受一个字符串参数 $text,代表可能包含 HTML A 元素的内容。
  • 返回值:返回转换后的内容字符串。
  • 内部机制:使用 preg_replace_callback 和 wp_rel_callback 函数处理链接,并涉及 stripslashes 和 wp_slash 进行转义处理。
  • 引入版本:自 WordPress 5.3.0 起可用。

代码示例

function wp_rel_ugc( $text ) {
    // This is a pre-save filter, so text is already escaped.
    $text = stripslashes( $text );
    $text = preg_replace_callback(
        '||i',
        static function ( $matches ) {
            return wp_rel_callback( $matches, 'nofollow ugc' );
        },
        $text
    );
    return wp_slash( $text );
}

注意事项

  • 此函数是预保存过滤器,输入文本已转义,需先使用 stripslashes 处理。
  • 依赖 wp_rel_callback 和 wp_slash 函数,确保正确添加属性和转义输出。
  • 主要用于处理用户生成内容,帮助搜索引擎识别链接性质。

📄 原文内容

Adds rel="nofollow ugc" string to all HTML A elements in content.

Parameters

$textstringrequired
Content that may contain HTML A elements.

Return

string Converted content.

Source

function wp_rel_ugc( $text ) {
	// This is a pre-save filter, so text is already escaped.
	$text = stripslashes( $text );
	$text = preg_replace_callback(
		'|<a (.+?)>|i',
		static function ( $matches ) {
			return wp_rel_callback( $matches, 'nofollow ugc' );
		},
		$text
	);
	return wp_slash( $text );
}

Changelog

Version Description
5.3.0 Introduced.