wordpress主题文章下方都会显示标签,文章tag标签不但可以为文章分类划分,也是有利于网站的SEO,总之tag标签用对了好处是很多的。平时我们发文章都需要手动选择设置tag标签,有些麻烦,下面BOBO就教大家用一段代码给WordPress新发布的文章自动添加标签。
标签(tags)
是另一种形式的分类方法,WordPress自动为文章添加tags标签原理是从文章或标题中提取与数据库相关的tags标签的词。
WordPress新发布的文章自动添加标签方法步骤:
- 登录自己WordPress网站的后台。
- 进入外观—>编辑—>模板函数functions.php文件。
- 将下面的给WordPress新发布的文章自动添加标签代码复制到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 );
}
}
}
二、根据文章标题关键词提取标签
add_action('save_post', 'auto_add_tags');
function auto_add_tags(){
$tags = get_tags( array('hide_empty' => false) );
$post_id = get_the_ID();
$post_title = get_post($post_id)->post_title;
if ($tags) {
foreach ( $tags as $tag ) {
// 如果文章标题出现了已使用过的标签,自动添加这些标签
if ( strpos($post_title, $tag->name) !== false)
wp_set_post_tags( $post_id, $tag->name, true );
}
}
}
三、根据文章内容关键词提取标签,加链接
$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 = "";
$limit = rand($match_num_from,$match_num_to);
$content = preg_replace( '|(]+>)(.*)('.$ex_word.')(.*)(]*>)|U'.$case, '$1$2$4$5', $content);
$content = preg_replace( '|()|U'.$case, '$1$2$4$5', $content);
$cleankeyword = preg_quote($cleankeyword,'\'');
$regEx = '\'(?!((<.*?)|(]*?)>)|([^>]*?))\'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);
注:这种方式只能对新增文章生效,旧文章要更新才可以。
//将大小写强行更改为标签的大小写
$content = str_ireplace(urldecode($tag->slug), $tag->name, $content);
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)