文章出现tags标签,WordPress自动给文章添加tags内链

众所周知,网站内的链接(指网站内相关信息的互联)非常重要,也非常有利于用户的访问。你可以在链接中加入一些文章中出现的关键点,让这些重要的信息被用户点击看到,从而增强网站内容的粘性,让用户更容易找到你的内容。

如果我们手动添加关键词的链接,这无疑是一项非常繁琐的工作,所以我们让wordpress主题通过代码自动将文章中存在的标签添加到链接中。

$match_num_from = 1;
$match_num_to = 1;
function hx_tag_sort($a, $b){
    if ( $a->name == $b->name ) return 0;
    return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
}
function hx_tag_link($content){
    global $match_num_from,$match_num_to;
    $posttags = get_the_tags();
    if ($posttags) {
        usort($posttags, "hx_tag_sort");
        foreach($posttags as $tag) {
            $link = get_tag_link($tag->term_id);
            $keyword = $tag->name;
            $cleankeyword = stripslashes($keyword);
            $url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('【查看含有[%s]标签的文章】'))."\"";
            $url .= ' target="_blank"';
            $url .= ">".addcslashes($cleankeyword, '$')."</a>";
            $limit = rand($match_num_from,$match_num_to);
            $content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
            $content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
            $cleankeyword = preg_quote($cleankeyword,'\'');
            $regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
            $content = preg_replace($regEx,$url,$content,$limit);
            $content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
        }
    }
    return $content;
}
add_filter('the_content','hx_tag_link',1);

虽然市面上很多开源的CMS系统已经非常成熟,并且有内部链接或者相应插件的功能,但是也有一些自己开发的网站程序不具备自动添加内部链接的功能。它们如何实现?然后,经过我爱主题网近年来的探索和研究,终于取得了一些成果。这里提供了另一个方案,我已经在用了,但是没有打开插件。如果需要,我可以联系定制插件服务。

$keys =array(
    array('测试','http://www.ok.com/'),

);
$str ="这是是测试内容";
echo $str,"<br>";
foreach($keys as $nkeys){
    if(strpos($str,$nkeys[0]) ){
        $str =str_replace($nkeys[0],"<a href=http://www.ok.com/".$nkeys[1]." target=_blank >".$nkeys[0]."</a>",$str);
    }
}
echo $str;
我爱主题网 自2012
主题:260+ 销售:1000+
兼容浏览器

电话咨询

7*12服务咨询电话:

133-7205-6573

微信咨询