WordPress的API:在帖子上添加/删除标签

问题描述:

我知道它看起来像一个简单的操作,但我找不到任何资源或文档解释如何使用帖子ID以编程方式添加和删除标签到帖子。WordPress的API:在帖子上添加/删除标签

下面是我使用的是什么样的样本,但它似乎覆盖所有其他标记...

function addTerm($id, $tax, $term) { 

    $term_id = is_term($term); 
    $term_id = intval($term_id); 
    if (!$term_id) { 
     $term_id = wp_insert_term($term, $tax); 
     $term_id = $term_id['term_id']; 
     $term_id = intval($term_id); 
    } 
    $result = wp_set_object_terms($id, array($term_id), $tax, FALSE); 

    return $result; 
} 

您需要首先调用get_object_terms来获取已经存在的所有条款。

更新代码

function addTerm($id, $tax, $term) { 

    $term_id = is_term($term); 
    $term_id = intval($term_id); 
    if (!$term_id) { 
     $term_id = wp_insert_term($term, $tax); 
     $term_id = $term_id['term_id']; 
     $term_id = intval($term_id); 
    } 

    // get the list of terms already on this object: 
    $terms = wp_get_object_terms($id, $tax) 
    $terms[] = $term_id; 

    $result = wp_set_object_terms($id, $terms, $tax, FALSE); 

    return $result; 
} 
+0

FYI:is_term已更改为term_exists – Brad 2010-07-10 04:35:13

+3

哪里是这样的 “删除标签” 的一部分? – 2012-01-25 20:42:20

+0

有关我如何删除标签,请参阅http://wordpress.stackexchange.com/a/49256/9142。 – 2012-05-11 21:25:30

尝试使用wp_add_post_tags($post_id,$tags);

这是我如何做到这一点:

$tag="This is the tag" 
$PostId=1; // 
wp_set_object_terms($PostId, array($tag), 'post_tag', true); 

注:wp_set_object_terms()预计,第二个参数是一个数组。

如果你不知道帖子ID?你只是想添加标签到所有创建的新帖子?

在使用WordPress的API函数add_action('publish_post', 'your_wp_function');,你会自动调用该函数获得注入作为第一个参数的post_id

function your_wp_function($postid) { 
} 

其实,wp_set_object_terms可以处理你需要的一切本身:

如果您确实需要单独的功能:

function addTag($post_id, $term, $tax='post_tag') { 
    return wp_set_object_terms($post_id, $term, $tax, TRUE); 
} 

wp_set_object_terms的参数:

  1. 邮政ID
  2. 接受...
    • 一个字符串(例如'Awesome Posts')
    • 现有标记(例如1)的单个ID或
    • 任一(例如数组(“Awesome Posts”,1))的数组。
    • 注意:如果您提供一个非ID,它会自动创建标签。
  3. 分类法(例如,对于默认标签,使用'post_tag')。
  4. 是否......
    • FALSE)全部替换现有条款所提供的那些,或
    • TRUE_)附加/添加到现有的条款。

快乐编码!

由于WordPress 3.6中有wp_remove_object_terms($object_id, $terms, $taxonomy)这样做。

$terms参数表示slug(s)term(s)ID(s)移除并接受阵列,int或字符串。

来源:http://codex.wordpress.org/Function_Reference/wp_remove_object_terms