更新,代码现在可以工作了。
我有以下代码,但显然它没有按预期工作。它应该只从分类法 TAXONOMY_NAME 中获取自定义帖子类型 CUSTOM_POST_TYPE 的术语并添加为标签。
add_action('save_post','add_tags_auto');
function add_tags_auto($id) {
$terms = get_the_terms( $post->id, 'TAXONOMY_NAME' ); // get an array of all the terms as objects.
$add_tags = array();
foreach( $terms as $term ) {
$add_tags[] = $term->slug; // save the slugs in an array
}
$temp = array();
$tags = get_the_tags($id);
if ($tags) {
foreach ($tags as $tag)
$temp[] = $tag->name;
}
$tags = $temp;
$post = get_post($id);
if ($post->post_type != 'CUSTOM_POST_TYPE')
return false;
foreach ($add_tags as $t)
if (!in_array($t,$tags))
wp_add_post_tags($id,$add_tags);
}
最佳答案
这是未经测试的,但它应该是朝着正确方向迈出的一步,我已经做了一些调整并发表评论:
<?php
add_action('save_post','add_tags_auto');
function add_tags_auto($post_id) {
$post = get_post($post_id);
// bail if this isn't a type of post we want to auto-tag
if($post->post_type != 'CUSTOM_POST_TYPE')
return false;
// --------------------------------------------------
// get the list of tag names from the post
// --------------------------------------------------
$tagNames = array();
$tags = get_the_tags($post_id);
foreach($tags as $tag)
$tagNames[] = $tag->name;
// --------------------------------------------------
// get the list slugs from terms in the post, any
// slugs that aren't alredy a tag, will be marked for
// addition automatically
// --------------------------------------------------
$tagsToAdd = array();
foreach(get_the_terms($post_id, 'TAXONOMY_NAME') as $term)
if(!in_array($term->slug, $tagNames))
$tagsToAdd[] = $term->slug;
// if we have some new tags to add, let's do that now
if(!empty($tagsToAdd))
wp_add_post_tags($post_id, implode(',', $tagsToAdd));
}
我在您的代码中看到的一个潜在问题是设置 $post after 尝试使用它。我很确定在函数的第一行调用 $post->id 时,PHP 会发出警告,指出 $post 不是对象。因此,我将对 get_post 的调用移到了函数的顶部。
我添加的一个小调整是如果帖子不是所需的类型则提前返回。最好尽快执行此操作,而不是花时间进行可能会被进一步检查丢弃的计算。
我还合并了 foreach 循环的数量并重命名了一些变量以进行说明。我在您的原始代码中看到的唯一可能未按预期工作的另一件事是对 wp_add_post_tags 的调用,it's documented以逗号分隔的字符串作为第二个参数,而不是数组。
关于php - wordpress - 在保存后自动插入术语 slug 作为标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8437382/