load taxonomy term by name drupal 8

Solutions on MaxInterview for load taxonomy term by name drupal 8 by the best coders in the world

showing results for - "load taxonomy term by name drupal 8"
Valentina
29 Mar 2020
1  /**
2   * Utility: find term by name and vid.
3   *
4   * @param string $name
5   *   Term name.
6   * @param string $vid
7   *   Term vid.
8   *
9   * @return int
10   *   Term id, or 0 if none.
11   */
12  public static function getTidByName($name = NULL, $vid = NULL) {
13    if (empty($name) || empty($vid)) {
14      return 0;
15    }
16    $properties = [
17      'name' => $name,
18      'vid' => $vid,
19    ];
20    $terms = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term')->loadByProperties($properties);
21    $term = reset($terms);
22    return !empty($term) ? $term->id() : 0;
23  }
24