原文来源:https://www.wpdaxue.com/auto-add-tags.html
function array2object($array) { // 数组转对象
if (is_array($array)) {
$obj = new StdClass();
foreach ($array as $key => $val) {
$obj->$key = $val;
}
return $obj;
}
return $array;
}
function object2array($object) { // 对象转数组
if (is_object($object)) {
$array = array();
foreach ($object as $key => $value) {
$array[$key] = $value;
}
return $array;
}
return $object;
}
add_action('save_post', 'auto_add_tags');
function auto_add_tags($post_id) {
// 确保只处理文章类型为 'post' 的文章
if (get_post_type($post_id) !== 'post') {
return;
}
$tags = get_tags(array('hide_empty' => false));
$post_content = get_post_field('post_content', $post_id);
if ($tags) {
$i = 1;
$arrs = object2array($tags);
shuffle($arrs); // 如果需要打乱顺序,保留此行
$tags = array2object($arrs);
foreach ($tags as $tag) {
// 如果文章内容出现了已使用过的标签,自动添加这些标签
if (strpos($post_content, $tag->name) !== false) {
if ($i > 15) { // 控制输出数量
break;
}
// 检查是否已经存在该标签
if (!has_tag($tag->term_id, $post_id)) {
wp_set_post_tags($post_id, $tag->name, true);
}
$i++;
}
}
}
}