Title: get_cat_id   wp_insert_term custom function
Last modified: August 20, 2016

---

# get_cat_id wp_insert_term custom function

 *  [dbough](https://wordpress.org/support/users/dbough/)
 * (@dbough)
 * [14 years, 1 month ago](https://wordpress.org/support/topic/get_cat_id-wp_insert_term-custom-function/)
 * Greetings,
 * First, I’m fairly new to programming, keep that in mind.
 * I’ve written the function below which is meant to determine if a category exists,
   and if not create it. In either case we should return the category ID.
 *     ```
       function category_check($term){
       		if (!term_exists($term, "category")) {
       			$arg = array('description' => ucfirst($term) . ' on Amazon.com', 'parent' => "0");
         			$term = wp_insert_term(ucfirst($term), "category", $args);
         			return $i;
         		}else {
         		$i = get_cat_id($term);
         		return $i;
         		}
       }
       ```
   
 * Basically, I’m looping through a list of words. We look at the database to see
   if the term already exists, if not we add it, if it does, we return the ID. This
   will not work for ‘new’ terms on the first pass. It looks like its adding the
   term, but not returning the ID. If the term does exist, the ID returns as expected.
 * I’m sure it’s due to the syntax of my function, but haven’t been able to hammer
   it out.
 * Any help is appreciated =)

Viewing 1 replies (of 1 total)

 *  Thread Starter [dbough](https://wordpress.org/support/users/dbough/)
 * (@dbough)
 * [14 years, 1 month ago](https://wordpress.org/support/topic/get_cat_id-wp_insert_term-custom-function/#post-2689199)
 * Of course, as soon as I stared at it again, I noticed some flaws in the function.
   Tweaked it and got it to work:
 *     ```
       function category_check($term){
       		if (!term_exists($term, "category")) {
       			$arg = array('description' => ucfirst($term) . ' on Amazon.com', 'parent' => "0");
         			wp_insert_term(ucfirst($term), "category", $args);
       		}
       		$i = get_cat_id($term);
       		return $i;
       }
       ```
   
 * Not quite sure what it’s doing functionally, but I get what I expected. Guess
   I need to go ‘read a book’ 😉

Viewing 1 replies (of 1 total)

The topic ‘get_cat_id wp_insert_term custom function’ is closed to new replies.

## Tags

 * [get_cat_ID](https://wordpress.org/support/topic-tag/get_cat_id/)
 * [wp_insert_term](https://wordpress.org/support/topic-tag/wp_insert_term/)

 * In: [Fixing WordPress](https://wordpress.org/support/forum/how-to-and-troubleshooting/)
 * 1 reply
 * 1 participant
 * Last reply from: [dbough](https://wordpress.org/support/users/dbough/)
 * Last activity: [14 years, 1 month ago](https://wordpress.org/support/topic/get_cat_id-wp_insert_term-custom-function/#post-2689199)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
