本文最后更新于 2021年4月14日 by 阿喵
每次给文章加tag都特别头大,现在好了,有大神搞了个代码自动加提取文章中的tag,只要放到function.php中即可。
提交文章的时候,就会自动添加了。
将代码添加到主题的 functions.php 即可:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/** * WordPress 自动为文章添加已使用过的标签 * https://www.wpdaxue.com/auto-add-tags.html */ 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 ); } } } |
修改后可控制标签输出数量。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// WordPress 自动为文章添加已使用过的标签 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) { $i = 0; foreach ( $tags as $tag ) { // 如果文章内容出现了已使用过的标签,自动添加这些标签 if ( strpos($post_content, $tag->name) !== false){ if ($i == 5) { // 控制输出数量 break; } wp_set_post_tags( $post_id, $tag->name, true ); $i++; } } } } |
但这样输出,会默认输出前几个标签,考虑到每次输出都是标签库里面的前几个标签,不利于 SEO ,增加了标签打乱功能。
标签打乱增强版:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
// WordPress 自动为文章添加已使用过的标签
function array2object($array) { // 数组转对象
if (is_array($array)) {
$obj = new StdClass();
foreach ($array as $key => $val){
$obj->$key = $val;
}
}
else {
$obj = $array;
}
return $obj;
}
function object2array($object) { // 对象转数组
if (is_object($object)) {
foreach ($object as $key => $value) {
$array[$key] = $value;
}
}
else {
$array = $object;
}
return $array;
}
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) {
$i = 0;
$arrs = object2array($tags);shuffle($arrs);$tags = array2object($arrs);// 打乱顺序
foreach ( $tags as $tag ) {
// 如果文章内容出现了已使用过的标签,自动添加这些标签
if ( strpos($post_content, $tag->name) !== false){
if ($i == 5) { // 控制输出数量
break;
}
wp_set_post_tags( $post_id, $tag->name, true );
$i++;
}
}
}
}
|
@大朗
转自https://www.nbmao.com/archives/3814
声明:本站为个人非盈利博客,资源均网络收集且免费分享无限制,无需登录。资源仅供测试学习,请于24小时内删除,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集。请支持正版!如若侵犯了您的合法权益,可联系我们处理。









