Skip to main content

How do you retrieve a taxonomy term tid value from it's name?

In this situation, use the loadByProperties function.  Load the taxonomy term and then reset the array.

Note, reset - to set the internal pointer of an array to its first element.

See as follows:

    /**
     * Get the taxonomy term object by the name
     *
     * @param string $term_name Vocabulary term.
     *
     * @return any Term.tid
     */
    public function taxonomyTermByName($term_name)
    {
        if (is_null($term_name)) {
            return null;
        }
        $terms = \Drupal::entityTypeManager()
            ->getStorage('taxonomy_term')
            ->loadByProperties(['name' => $term_name]);
        $term = reset($terms);

        return $term->tid->value;
    }

The return value here could be $term.  Or in this instance, when calling the function I wanted to always retrieve the term.tid value.

Related articles