A-A+
wordpress纯代码实现tag关键词自动描文本
描文本对于SEO的优化至关重要,不管是文字关键词还是图片都应该加上描文本,只要描文本应用合理,对于SEO的优化会有很大帮助,在 wordpress 系统中应用 tag 来做关键词描文本是个不错的选择,不少做SEO的站长都在使用一款 WP keyword Link Plugin的wordpress自动描文本插件,其实这种自动描文本可以用纯代码来实现,实例代码如下:
$match_num_from = 1; //每篇文章中的关键词数量低于多少则不描文本(请不要低于1) $match_num_to = 1; //同一篇文章中,同一个关键词最多描几次文本(这里是1次,建议不超过2次) add_filter('the_content','tag_link',1); function tag_sort($a, $b){ if ( $a->name == $b->name ) return 0; return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1; } function tag_link($content){ global $match_num_from,$match_num_to; $posttags = get_the_tags(); if ($posttags) { usort($posttags, "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, '$'),__('View all posts in %s'))."\""; $url .= ' target="_blank" class="tag_link"'; $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; }
这段代码的意思只会应用在已存在的 tag 上面文本,如果需要定义其它描文本的话就只能使用插件了,将这段代码加入到主题 functions.php 文件中即可。