代码之家  ›  专栏  ›  技术社区  ›  st4ck0v3rfl0w

wordpress api:添加/删除帖子上的标记

  •  12
  • st4ck0v3rfl0w  · 技术社区  · 15 年前

    我知道这看起来是一个简单的操作,但是我找不到任何资源或文档来解释如何使用post id以编程方式向post添加和删除标记。

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

    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;
    }
    
    6 回复  |  直到 9 年前
        1
  •  5
  •   Byron Whitlock    15 年前

    你得先打电话 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;
    }
    
        2
  •  4
  •   streetparade    15 年前

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

        3
  •  2
  •   Ram Sharma    9 年前

    我是这样做的:

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

    注: wp_set_object_terms() 期望第二个参数是数组。

        4
  •  2
  •   Ram Sharma    9 年前

    从WordPress3.6开始 wp_remove_object_terms( $object_id, $terms, $taxonomy ) 那就是真的。

    这个 $terms 参数表示 slug(s) ID(s) term(s) 删除并接受数组、int或string。

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

        5
  •  1
  •   stealthyninja michkra    13 年前

    如果你不知道邮政编码怎么办?您只想将标记添加到所有创建的新帖子中吗?

    使用wordpress api函数时 add_action('publish_post', 'your_wp_function'); ,调用的函数将自动获取 post_id 作为第一个参数注入:

    function your_wp_function($postid) {
    }
    
        6
  •  1
  •   Nathan J.B. Dogbert    12 年前

    事实上, 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. 岗位身份证
    2. 接受…
      • 一个字符串(例如“棒极了的帖子”)
      • 现有标记的单个ID(例如1),或
      • 任意一个数组(例如数组('awesome posts',1))。
      • 注: 如果你提供一个非身份证,它 自动创建标记。
    3. 分类法(例如,对于默认标记,使用“post_tag”)。
    4. 是否…
      • ( FALSE )用提供的条款替换所有现有条款,或
      • ( TRUE_ )附加/添加到现有条款。

    快乐编码!