Tag标签对于网站的seo有着非常重要的作用,但是有很多站长在写文章的时候不去添加标签,主要是因为每篇文章手动添加tag太麻烦了,说白了就是懒。
下面为大家提供一种方法,自动添加已经用过的标签,同时给标签添加内链。
将以下两段代码放到主题的functions.php文件最后一个?>即可。
代码一:自动为文章添加以前用过的标签,只要文章中出现了某些词语,是以前设置过标签的,在本文将自动设置为标签。所以要想该功能能充分发挥作用,需要在以前设置过足够多的标签,不过这东西是可以慢慢积累的。
/* 自动为文章添加标签 */
add_action('save_post', 'auto_add_tags');
function auto_add_tags(){
$tags = get_tags( array('hide_empty' => false) );
$post_id = get_the_ID();
$post_content = get_post($post_id)->post_content;
if ($tags) {
foreach ( $tags as $tag ) {
// 如果文章内容出现了已使用过的标签,自动添加这些标签
if ( strpos($post_content, $tag->name) !== false)
wp_set_post_tags( $post_id, $tag->name, true );
}
}
}
代码二:为设置的标签自动添加内链,强化SEO很简单,不做解释了。
/* 自动为文章内的标签添加内链 */
$match_num_from = 1; //一篇文章中同一个标签少于几次不自动链接
$match_num_to = 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, '$'),__('【查看含有[%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','tag_link',1);
依米资源网是一个免费资源平台,1米为收集整理的费用。本站所有资源均来自于互联网,版权归原作者所有,请于下载24小时之内删除,请勿商用,支持正版。
依米资源网 » wordpress纯代码实现文章自动添加标签 并自动添加标签内链
依米资源网 » wordpress纯代码实现文章自动添加标签 并自动添加标签内链
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 依米资源网