Showing posts with label categories. Show all posts
Showing posts with label categories. Show all posts

Friday, August 22, 2008

Programmatically create drupal term

Ever wanted to programmatically create drupal term? Here is the code snippet. Just call the below function by passing vocabulary id under which you want to create term.

function term_create($vid)
{
$edit = array ("vid" => $vid, "name" => $term_name);
taxonomy_save_term($edit);
}

Of course, you have to run this in a drupal environment, which means that you should have bootstrapped drupal before using the above function.

One issue with the above function is it uses vocabulary id, which we don't have/know most of the time. There is a quick solution. You can use below function to get vocabulary id from name.


function get_vocabulary_id ($vname)
{
$results = db_query('SELECT * FROM {vocabulary} WHERE name = "%s"', $vname);
if($results)
{
$res=db_fetch_object($results);
return $res->vid;
}
else
{
return null;
}
}

About drupal categories and subcategories

Drupal has an excellent way of classifying data. You can create a classification tree structures of whatever depth you want and arrange your data in the structures.

The problem: In the administration panel, you never see anything like classifications or categories.

Well, drupal calls it in a different name.

The root node of such structure is called vocabulary. The child nodes are called terms.

Administration (create/edit/update) of vocabulary and terms are available under Taxonomy.