//------get term/taxonomy data
$term_name = \'Uncategorized\';
$term_slug = \'Default category slug\'; //this gets sanitized by the blp_wordpress_insert_term function!
$term_taxonomy = \'category\';
$term_description = $term_name . " desc here.. ";
$term_parentID = 0;
//------byref stuff: library function will populate them in return
$term_id = null;
$term_taxonomy_id = null;
$term_error = null;
//------call the library function
if (blp_wordpress_insert_term($term_name,$term_slug,$term_taxonomy,$term_description,$term_parentID,$term_id,$term_taxonomy_id,$term_error)):
echo "<p>" , "The term <i>{$term_name}</i> under the <i>{$term_taxonomy}</i> taxonomy has been added into the <i>wp_terms & wp_term_taxonomy<i> tables. The Term ID is {$term_id} and the related taxonomy ID is {$term_taxonomy_id}.";
else:
echo "<p>" , $term_error;
die;
endif;
//-----------------------------here is the library function
function blp_wordpress_insert_term($term_name,$term_slug,$term_taxonomy,$term_description,$term_parentID,&$term_id,&$term_taxonomy_id,&$term_error){
/*
inserts a term under the given taxonomy and returns the term_id and term_taxonomy_id byref if everything is cool/
it also returns as TRUE or FALSE as a whole depending on a proper entry
it also populates the $term_error variable - passed byref if an error occurs
TO DO: validate the passed parentid to see if its a valid ID
*/
$term_slug = sanitize_title($term_name, $term_slug);
if ( term_exists( $term_name , $term_taxonomy ) ):
$term_error = "ERROR: The term ({$term_name}) already exists!";
return false;
else:
if (taxonomy_exists($term_taxonomy)): //insert the term into the wp_terms
$args = array(
\'description\' => $term_description,
\'slug\' => $term_slug,
\'parent\' => $term_parentID
);
$result = wp_insert_term($term_name, $term_taxonomy, $args);
//print_r ($result); // Array ( [term_id] => 1 [term_taxonomy_id] => 1 )
if ( is_wp_error( $result ) ):
$term_error = "ERROR: " . $result->get_error_message();
return false;
else:
$term_id = $result[\'term_id\'];
$term_taxonomy_id = $result[\'term_taxonomy_id\'];
return true;
endif;
else:
$term_error = "ERROR: The taxonomy {$term_taxonomy} does not exist. blp_wordpress_insert_term cannot add a term when its associated taxonomy missing. Use the <i>register_taxonomy</i> function to register the taxonomy <i>{$term_taxonomy}. ";
return false;
endif;
endif;
}