2010-03-12 61 views
12

我知道它看起來像一個簡單的操作,但我找不到任何資源或文檔解釋如何使用帖子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; 
} 

回答

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

2

這是我如何做到這一點:

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

注:wp_set_object_terms()預計,第二個參數是一個數組。

1

如果你不知道帖子ID?你只是想添加標籤到所有創建的新帖子?

在使用WordPress的API函數add_action('publish_post', 'your_wp_function');,你會自動調用該函數獲得注入作爲第一個參數的post_id

function your_wp_function($postid) { 
} 
1

其實,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_)附加/添加到現有的條款。

快樂編碼!

相關問題