Wordpress API:在帖子上添加/删除标签 [英] Wordpress API: Add / Remove Tags on Posts

查看:27
本文介绍了Wordpress API:在帖子上添加/删除标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know it seems like a simple operation, but I can't find any resource or documentation that explains how to programmatically add and remove tags to a post using the post ID.

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

Below is a sample of what I'm using, but it seems to overwrite all the other tags...

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 获取所有已经存在的术语.

You need to first call get_object_terms to get all the terms that exist already.

更新代码

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;
}

这篇关于Wordpress API:在帖子上添加/删除标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆