2010-06-09 10 views
7

मेरा लक्ष्य केवल वर्डप्रेस में श्रेणी मौजूद है या नहीं, यह जांचने के लिए कुछ प्रकार की डिफ़ॉल्ट विधि का उपयोग करना है, और यदि यह नहीं है, तो श्रेणी जोड़ें। टैग के साथ ही।वर्डप्रेस: ​​यदि वे मौजूद नहीं हैं तो स्वचालित रूप से श्रेणी और टैग डालें?

<?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

Sory श्रेणी बनाने के लिए, बयान के लिए कोड में डाल नहीं किया है: user351297

उत्तर

9

आप बस दौड़ सकते हैं;

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

फ़ंक्शन उस शब्द को जोड़ नहीं देगा यदि यह पहले से ही उस वर्गीकरण के लिए मौजूद है!

ब्याज से, आप अपनी प्लगइन में इस तरह के कोड को कब कॉल करेंगे? सुनिश्चित करें कि आप इसे सक्रियण हुक फ़ंक्शन के भीतर पंजीकृत करते हैं, अन्यथा यह प्रत्येक लोड पर चलाएगा!

अद्यतन

स्लग द्वारा एक शब्द की आईडी प्राप्त करने के लिए, उपयोग;

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

शब्द के वर्गीकरण के साथ 'वर्गीकरण' को बदलें - अपने मामले में, 'श्रेणी'।

+0

मैन, क्या माता-पिता के लिए स्लग का उपयोग करने की संभावना है? या स्लग विशेषता का उपयोग करने वाले कोड को चारों ओर बदलना? क्योंकि मुझे आईडी को मानने के लिए मैन्युअल रूप से कोड सेट करना होगा और शुरुआत में मूल शब्द डालना होगा (केवल स्लग नाम जानने के बजाय)। – user351297

+0

कोई जांच नहीं - अद्यतन उत्तर की जांच करें :) – TheDeadMedic

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); 
संबंधित मुद्दे