Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress: Insert Category & Tags Automatically if They Don't Exist?

Tags:

wordpress

My goal is just to use some type of default method for checking if category exist in Wordpress, and if it doesn't, add the category. Same with tags.

Here is a mess I made trying to make it happen:

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

I plan to add this as a plugin. Any thoughts or help would be great!

like image 932
user351297 Avatar asked Jun 09 '10 21:06

user351297


2 Answers

You can just run;

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

The function won't add the term if it already exists for that taxonomy!

Out of interest, when will you be calling this kind of code in your plugin? Make sure you register it within an activation hook function, otherwise it'll run on every load!

UPDATE

To get the ID of a term by slug, use;

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

Replace 'taxonomy' with the taxonomy of the term - in your case, 'category'.

like image 51
TheDeadMedic Avatar answered Oct 06 '22 06:10

TheDeadMedic


Here is how to assign and create the category if not exists

$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 );
like image 24
Atef Avatar answered Oct 06 '22 07:10

Atef