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

st4*_*l0w 12 php wordpress wordpress-plugin

我知道这似乎是一个简单的操作,但我找不到任何资源或文档,解释如何使用帖子ID以编程方式添加和删除标签.

下面是我正在使用的示例,但它似乎覆盖了所有其他标签......

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;
}
Run Code Online (Sandbox Code Playgroud)

Byr*_*ock 5

您需要先调用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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这个"删除标签"的一部分在哪里? (3认同)