programmatically create or add new Taxonomy Terms in drupal

To create a new taxonomy term through PHP you can use taxonomy_save_term(&$form_values) which is mainly intended for use as a helper function to by the real drupal taxonomy add term form.
The relevant term details are passed as parameter and the Term Id of the newly created taxonomy term is placed back in this array and can be accessed by the calling code.

here I explain small code to assign taxonomy term to node if taxonomy is new , first you save in taxonomy in db.

/**
* Save Node
*/
foreach($arrNodeIds as $intNodeId){
$objNodeInfo = node_load($intNodeId);
$arrTermsIds = getTermIds($_POST['txt_tag_val_'.$intNodeId]);
$objNodeInfo->taxonomy = $arrTermsIds;
node_save($objNodeInfo);
}
/**
* See If the term exists in the chosen vocabulary and return the tid; otherwise, add a new record.
* @param $strTerms
* - Terms Name
* @return
* - Terms Ids
*/
function getTermIds($strTerms){
$arrTerms = explode(",",$strTerms);
if(!is_array($arrTerms)){
$arrTerms[0] = $strTerms;
}
foreach ($arrTerms as $strTerm){
if(strlen($strTerm) > 0){
$possibilities = taxonomy_get_term_by_name(trim($strTerm));
$intTermTid = NULL;
foreach ($possibilities as $possibility){
$intTermTid = $possibility->tid;
}
// Check new term , If yes then insert this new term in db
if (!$intTermTid){
$arrParam = array('vid' => 2, 'name' => $strTerm);
$status = taxonomy_save_term($arrParam);
$intTermTid = $arrParam['tid'];
}
$arrTermIds[] = $intTermTid;
}
}
return $arrTermIds;
}

/**
* add a new record as Term of Texonomy.
* @param $arrParam
* - param (vid , name)
* @return
* - status
*/
function addTaxonomyTerm($arrParam){
$vid = $arrParam['vid'];
$name = trim($arrParam['name']);
return taxonomy_save_term($form_values);
}

No comments: