Wordpress: automatically add categories and tags if they do not exist?

My goal is to use some type of default method to check for a category in Wordpress, and if not, add a category. Same thing with tags.

Here is the mess I tried to do this:

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

+7
wordpress wordpress-plugin
source share
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 will not add a term if it already exists for this taxonomy!

Of interest, when will you name this code in your plugin? Make sure you register it in the activation activation function, otherwise it will work on every boot!

UPDATE

To get the identifier of the word 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 this term - in your case, "category".

+9
source share

Here's how to assign and create a category if it does not exist.

 $pid = 168; // post we will set it 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 get it id $cat_id = $cat->term_id ; } //setting post category $res=wp_set_post_terms($pid,array($cat_id),$taxonomy ,$append); var_dump( $res ); 
0
source share

All Articles