2010-06-09 63 views
7

我的目標是使用某種類型的默認方法來檢查Wordpress中是否存在類別,如果不存在,請添加類別。與標籤相同。WordPress的:如果他們不存在自動插入類別和標籤?

這裏是一個爛攤子我做出努力做到這一點:

<?php 
    if (is_term('football', 'category')) { 
    } 
    else (
     $new_cat = array('cat_name' => 'Football', 'category_description' => 'Football Blogs', 'category_nicename' => 'category-slug', 'category_parent' => 'sports'); 
     $my_cat_id = wp_insert_category($new_cat); 
    ) 

我打算將其添加爲插件。任何想法或幫助都會很棒!

+0

索裏,沒有把在代碼聲明: user351297 2010-06-09 21:35:47

回答

9

您可以運行;

wp_insert_term('football', 'category', array(
    'description' => 'Football Blogs', 
    'slug' => 'category-slug', 
    'parent' => 4 // must be the ID, not name 
)); 

如果該函數已經存在,該函數將不會添加該分類!

出於興趣,您何時會在您的插件中調用這種代碼?確保你在一個激活鉤子函數中註冊它,否則它會在每個負載上運行!

UPDATE

爲了通過嵌塊得到的一個術語的ID,使用;

$term_ID = 0; 
if ($term = get_term_by('slug', 'term_slug_name', 'taxonomy')) 
    $term_ID = $term->term_id; 

用術語的分類法替換'分類法' - 在你的案例中,'category'。

+0

男人,是否有可能爲家長使用slu??或者轉而使用slug屬性的代碼?因爲我將不得不手動設置代碼來承擔ID並在開頭插入父項(而不是僅僅知道子彈名稱)。 – user351297 2010-06-10 20:29:27

+0

沒有probs - 檢查更新的答案:) – TheDeadMedic 2010-06-10 21:07:51

0

下面是如何分配和創建類別如果不存在

$pid = 168; // post we will set it's categories 
$cat_name = 'lova'; // category name we want to assign the post to 
$taxonomy = 'category'; // category by default for posts for other custom post types like woo-commerce it is product_cat 
$append = true ;// true means it will add the cateogry beside already set categories. false will overwrite 

//get the category to check if exists 
$cat = get_term_by('name', $cat_name , $taxonomy); 

//check existence 
if($cat == false){ 

    //cateogry not exist create it 
    $cat = wp_insert_term($cat_name, $taxonomy); 

    //category id of inserted cat 
    $cat_id = $cat['term_id'] ; 

}else{ 

    //category already exists let's get it's id 
    $cat_id = $cat->term_id ; 
} 

//setting post category 
$res=wp_set_post_terms($pid,array($cat_id),$taxonomy ,$append); 

var_dump($res);