By admin |

Drupal并没有提供API来获得term的dpeth;但是我们仍然有方法获得。本文分享两种方法,供有需要读者自行选择。

1:自行构造函数,通过数据库查询方式来获得。

function get_term_depth($tid) {
 $limit = 9;
 $depth = 1;
 while($parent = db_query('SELECT parent FROM {taxonomy_term_hierarchy} WHERE tid = :tid', array(':tid' => $tid))->fetchField()) {
    $depth++;
    $tid = $parent;
    if($depth > $limit) {
      break;
    }
  }
  return $depth;
}

2:利用ctools

ctools有个子模块,叫做term_depth,估计大部分人都没注意过这个模块。这个模块提供一个隐藏的函数_term_depth,也可以用来计算term的depth。

经过一番摸索,下面提供可以调用该函数的方法。

ctools_plugin_load_function('ctools', 'access', 'term_depth', '_term_depth');
$tid = 2;
echo _term_depth($tid);

如下是ctools提供的_term_depth函数原型;用到了静态变量与递归函数,兼顾通用性与性能之间的平衡,值得借鉴。

function _term_depth($tid) {
  static $depths = array();

  if (!isset($depths[$tid])) {
    $parent = db_select('taxonomy_term_hierarchy', 'th')
      ->fields('th', array('parent'))
      ->condition('tid', $tid)
      ->execute()->fetchField();

    if ($parent == 0) {
      $depths[$tid] = 1;
    }
    else {
      $depths[$tid] = 1 + _term_depth($parent);
    }
  }

  return $depths[$tid];
}

完成此文后,经过调查,发现还有第三种方式获得term的深度,堪称神来之笔;不罗嗦了,代码如下:

count(taxonomy_get_parents_all($tid));

同时也发现相关讨论,链接如下,供参考。

https://www.drupal.org/node/886526


总结下,实现同一个目的,使用Drupal的话,一般情况下都至少有两种以上方案供选择。这样对初学者来说是很大的挑战;但是一旦完成这个挑战,则会完成自身华丽丽的提升。