Wordpress:限制帖子内容中的标签链接 [英] Wordpress: Limit Tag Links in Post Content
问题描述
我真的很沮丧,我是 wordpress 的新手,我正在尝试限制在帖子内容文章中出现的最大标签链接数.下面是我的代码.我不知道如何修复它.
I really frustrated, I am a novice in wordpress I am trying to Limit Maximum Numbers of Tag Links to appear within post content article. Below is my code. I don't know how to fix it up.
function link_words( $text ) {
$replace = array();
$tags = get_tags();
$count=0;
if ( $tags ) {
foreach ( $tags as $tag ) {
$count++;
$replace[ $tag->name ] = sprintf( '<a href="%s">%s</a>', esc_url( get_term_link( $tag ) ), esc_html( $tag->name ) );
if( $count > 2 ) break;
}
}
$text = str_replace( array_keys($replace), $replace, $text );
return $text;
}
add_filter( 'the_content', 'link_words' );
推荐答案
好的,我想我现在明白你想要什么了...
Ok, so I think I understand what you want better now...
function link_words( $text ) {
$tags = get_tags();
if ( $tags ) {
foreach ( $tags as $tag ) {
$from = '!<h2>[^<>]*<\/h2>(*SKIP)(*F)|<b>[^<>]*<\/b>(*SKIP)(*F)|<a\b[^>]*>.*?</a>(*SKIP)(*F)|(\b'.$tag->name.'\b)(?=[^>]*(?:<|$))!';
$to = sprintf( ' <a href="%s">%s</a> ', esc_url( get_term_link( $tag ) ), esc_html( $tag->name ) );
$text = preg_replace($from, $to , $text, 2);
}
}
return $text;
}
add_filter( 'the_content', 'link_words' );
由于 preg_replace (2) 的限制,并且它在标签循环内,这将替换文本中每个标签的标签名称的两个实例......这是否符合您的要求?请注意,这不是不区分大小写的,因此如果您的标签是句子中的第一个单词并且大写,则它将不匹配.要做这样的事情,也许看看这个线程:PHP preg_replace:不区分大小写的匹配和区分大小写的替换一个>
Because of the limit on preg_replace (2), and it being inside the tag-loop, this replaces two instances of a tag name in the text for every tag... Is this along the lines of what you want? Be aware that this is not case-insensitive, so it will not match if your tag is the first word in a sentence, and is capitalized. To do something like that, maybe take a look at this thread: PHP preg_replace: Case insensitive match with case sensitive replacement
这篇关于Wordpress:限制帖子内容中的标签链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!