2011-12-08 22 views
3

更新,代碼現在工作。wordpress - 自動插入術語slu as作爲標記上保存

我有下面的代碼,但遺忘它不能按預期工作。它應該將TAXONOMY_NAME分類中的術語僅用於自定義帖子類型CUSTOM_POST_TYPE並添加爲標籤。


add_action('save_post','add_tags_auto'); 
function add_tags_auto($id) { 

    $terms = get_the_terms($post->id, 'TAXONOMY_NAME'); // get an array of all the terms as objects. 
    $add_tags = array(); 

    foreach($terms as $term) { 
     $add_tags[] = $term->slug; // save the slugs in an array 
    } 
    $temp = array(); 
    $tags = get_the_tags($id); 
    if ($tags) { 
    foreach ($tags as $tag) 
     $temp[] = $tag->name; 
    } 
    $tags = $temp; 

    $post = get_post($id); 

    if ($post->post_type != 'CUSTOM_POST_TYPE') 
     return false; 

    foreach ($add_tags as $t) 
     if (!in_array($t,$tags)) 
      wp_add_post_tags($id,$add_tags); 
} 

回答

0

這是未經測試,但它應該是朝着正確方向邁出的一步,我做了一些調整,並發表評論:我與您的代碼看到

<?php 
add_action('save_post','add_tags_auto'); 
function add_tags_auto($post_id) { 
    $post = get_post($post_id); 

    // bail if this isn't a type of post we want to auto-tag 
    if($post->post_type != 'CUSTOM_POST_TYPE') 
     return false; 

    // -------------------------------------------------- 
    // get the list of tag names from the post 
    // -------------------------------------------------- 
    $tagNames = array(); 
    $tags  = get_the_tags($post_id); 

    foreach($tags as $tag) 
     $tagNames[] = $tag->name; 

    // -------------------------------------------------- 
    // get the list slugs from terms in the post, any 
    // slugs that aren't alredy a tag, will be marked for 
    // addition automatically 
    // -------------------------------------------------- 
    $tagsToAdd = array(); 
    foreach(get_the_terms($post_id, 'TAXONOMY_NAME') as $term) 
     if(!in_array($term->slug, $tagNames)) 
      $tagsToAdd[] = $term->slug; 

    // if we have some new tags to add, let's do that now 
    if(!empty($tagsToAdd)) 
     wp_add_post_tags($post_id, implode(',', $tagsToAdd)); 
} 

一個潛在的問題正在設置$後試圖使用它。我很確定當你的函數的第一行調用$ post-> id PHP提出的警告$ post是一個非對象。所以我把電話轉到get_post直到函數的頂部。

我添加的一個小小的調整是,如果帖子不是所需的類型,就會提前返回。最好儘快做到這一點,而不要花費時間進行計算,這些計算可能會被進一步的檢查所忽略。

我也合併了foreach循環的數量,並重新命名了一些變量以進行說明。我在原始代碼中看到的可能沒有按預期工作的唯一其他事情是調用wp_add_post_tagsit's documented以逗號分隔的字符串作爲第二個參數,而不是數組。

+0

是否有限制添加標籤的數量 –

+0

是的,您可以退出調用'$ tagsToAdd [] = $ term-> slug;'的foreach。假設你有一個變量,稱之爲'$ iMaxTags'(例如你可以從數據庫中填充它),循環中的條件變成'if($ i <$ iMaxTags &&!in_array($ term-> slug,$標記名))';那麼還要記住將foreach更改爲'as $ i => $ term'。 – quickshiftin

+0

但是,請注意,這是限制它們的一種相當粗糙的方式。一個實際的解決方案可能會試圖更加智能地過濾它們,這種或那種方式。 – quickshiftin