the_tags
云策文档标注
概述
the_tags 是一个 WordPress 过滤器,用于修改特定文章的标签列表输出。它允许开发者通过 Hook 自定义标签的显示格式或内容。
关键要点
- 过滤器名称:the_tags,用于过滤文章的标签列表。
- 参数:包括 $tag_list(标签列表字符串)、$before(标签前字符串)、$sep(标签分隔符)、$after(标签后字符串)和 $post_id(文章 ID)。
- 返回值:通过 apply_filters 返回过滤后的标签列表字符串。
- 相关函数:get_the_tag_list() 用于获取格式化后的标签字符串。
- 版本历史:自 WordPress 2.3.0 引入。
代码示例
add_filter( 'the_tags', 'my_filter_the_tags' );
function my_filter_the_tags( $html ) {
$dom = new DOMDocument();
$dom->loadHtml( $html );
$anchors = $dom->getElementsByTagName( 'a' );
$nb = $anchors->length;
for ( $pos = 0; $pos < $nb; $pos++ ) {
$anchors->item( $pos )->nodeValue = 'any_replacement';
}
$html = $dom->saveHTML();
return $html;
}注意事项
- 用户贡献笔记提供了使用 DOMDocument 或字符串操作来替换标签内容的示例,但需注意代码可能不完整或存在错误,建议在实际应用中测试和调整。
- 过滤器接收的 $html 参数是包含链接的标签字符串,操作时应确保不破坏链接结构。
原文内容
Filters the tags list for a given post.
Parameters
$tag_liststring-
List of tags.
$beforestring-
String to use before the tags.
$sepstring-
String to use between the tags.
$afterstring-
String to use after the tags.
$post_idint-
Post ID.
Source
return apply_filters( 'the_tags', $tag_list, $before, $sep, $after, $post_id );
Changelog
| Version | Description |
|---|---|
| 2.3.0 | Introduced. |
Skip to note 3 content
capbussat
The_tags receives an html string formed in this way:
$html = "<a href="<a href="http://my_website.local/tag/tag_one/"" rel="nofollow ugc">http://my_website.local/tag/tag_one/"</a>; rel="tag">tag_one</a>, <a href="<a href="http://my_website.local/tag/tag_two/"" rel="nofollow ugc">http://my_website.local/tag/tag_two/"</a>; rel="tag">tag_two</a>";In order to replace a tag you may use Clase DOMDocument. For example, you can replace all tags using a replacement word. but do not change the tag’s links. A more useful example can replace some tags by an alias or by a translation.
add_filter( 'the_tags', 'my_filter_the_tags'); function my_filter_the_tags( $html) { $dom = new DOMDocument(); $dom->loadHtml($html); $anchors = $dom->getElementsByTagName('a'); $nb = $anchors->length; for($pos=0; $pos<$nb; $pos++) { $anchors->item($pos)->nodeValue = 'any_replacement'; // check error_log( $anchors->item($pos)->nodeValue); } $html = $dom->saveHTML(); return $html; }output is this:
<pre class="wp-block-code"><code lang="php" class="language-php "><a href="http://my_website.local/tag/tag_one/"; rel=”tag”>any_replacement, <a href="http://my_website.local/tag/tag_two/"; rel=”tag”>any_replacement
Skip to note 4 content
capbussat
An easiest way to replace the_tags
add_filter( 'the_tags', 'my_filter_the_tags'); function my_filter_the_tags( $html) { $tags = get_tags(); $out = ''; foreach ( $tags as $key=>$tag) { $pos = strpos( $html , $tag->name ); if ( $pos > 0 ) { $replace = my_tag_translation($tag->name); $out .= '<a href = "'.site_url() .'/tag/' . $tag->slug . ' " rel="tag" title="" >' . $replace . ' ,</a> '; } } }