From 8b0bd2808b6aa6f3170f14100ce1c0496e799597 Mon Sep 17 00:00:00 2001
From: Marco Villegas <marvil07@gmail.com>
Date: Fri, 4 Nov 2011 04:39:52 -0500
Subject: [PATCH] Issue #143817 by webchick, marvil07: Added API: Get just
 term ID by name.

---
 core/modules/taxonomy/taxonomy.module |   58 +++++++++++++++++++++++++++++++++
 1 files changed, 58 insertions(+), 0 deletions(-)

diff --git a/core/modules/taxonomy/taxonomy.module b/core/modules/taxonomy/taxonomy.module
index eb20c26..3dba593 100644
--- a/core/modules/taxonomy/taxonomy.module
+++ b/core/modules/taxonomy/taxonomy.module
@@ -1072,6 +1072,64 @@ function taxonomy_get_term_by_name($name) {
 }
 
 /**
+ * Returns the term ID for the given term name.
+ *
+ * NOTE: If more than one match is found, this function will return the first
+ * one it finds. If you have duplicate term names in your database, you may
+ * wish to use the more robust taxonomy_get_term_by_name() instead.
+ *
+ * @param string $name
+ *   Name of the term to search for.
+ * @param mixed $vocabulary
+ *   A vocabulary machine name string or a integer representing the
+ *   vocabulary vid.
+ *
+ * @return
+ *   The term ID of the given term, or FALSE if none was found.
+ */
+function taxonomy_get_tid_by_name($name, $vocabulary=NULL) {
+  $tids_by_name = &drupal_static(__FUNCTION__);
+
+  if (isset($vocabulary)) {
+    if (is_int($vocabulary)) {
+      // It's a vid.
+      $query_type = 'vid';
+    }
+    else {
+      // It's a vocabulary machine name.
+      $query_type = 'machine_name';
+    }
+  }
+  else {
+    $query_type = 'general';
+    // Set $vocabulary to always use the general way to access our static
+    // cache.
+    $vocabulary = 0;
+  }
+  if (isset($tids_by_name[$name][$query_type][$vocabulary])) {
+    return $tids_by_name[$name][$query_type][$vocabulary];
+  }
+
+  $query = db_select('taxonomy_term_data', 't')
+    ->fields('t', array('tid'))
+    ->condition('t.name', db_like(trim($name)), 'LIKE')
+    ->addTag('term_access');
+
+  if ($query_type == 'vid') {
+    $query->condition('vid', $vocabulary);
+  }
+  elseif ($query_type == 'machine_name') {
+    $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid AND v.machine_name = :name', array(':name' => $vocabulary));
+  }
+
+  if ($tid = $query->execute()->fetchField()) {
+    $tids_by_name[$name][$query_type][$vocabulary] = $tid;
+  }
+
+  return $tid;
+}
+
+/**
  * Controller class for taxonomy terms.
  *
  * This extends the DrupalDefaultEntityController class. Only alteration is
-- 
1.7.7

