You are here

function synonyms_add_term_by_synonym in Synonyms 7

Look up a term considering synonyms and if nothing is found add one.

This function is useful for automated creation of new terms as it won't generate the same terms over and over again.

Parameters

string $name: The string to be searched for its {taxonomy_term_data}.tid

object $vocabulary: Fully loaded vocabulary object in which you wish to search

int $parent: Optional. In case you want to narrow your search scope, this parameter takes in the {taxonomy_term_data}.tid of the parent term, letting you search only among its children

Return value

int If a term already exists, its {taxonomy_term_data}.tid is returned, otherwise it creates a new term and returns its {taxonomy_term_data}.tid

1 call to synonyms_add_term_by_synonym()
SynonymsSynonymsWebTestCase::testSynonyms in ./synonyms.test
Test the functionality of synonyms.

File

./synonyms.module, line 647
Provide synonyms feature for Drupal entities.

Code

function synonyms_add_term_by_synonym($name, $vocabulary, $parent = 0) {
  if (!module_exists('taxonomy')) {
    return 0;
  }
  $tid = synonyms_get_term_by_synonym($name, $vocabulary, $parent);
  if ($tid) {

    // We found some term, returning its tid.
    return $tid;
  }

  // We haven't found any term, so we create one.
  $term = (object) array(
    'name' => $name,
    'vid' => $vocabulary->vid,
    'parent' => array(
      $parent,
    ),
  );
  taxonomy_term_save($term);
  if (isset($term->tid)) {
    return $term->tid;
  }

  // Normally we shouldn't reach up to here, because a term would have got
  // created and the just created tid would have been returned. Nevertheless,
  // as a fallback in case of any error we return 0.
  return 0;
}