添加 class 到 drupal 正文

Add class to drupal body

如何将与节点相关的所有术语的术语 ID 添加到 drupal 站点中的节点主体 class?

例如,名为 Whosebug 的节点被标记了四个术语

term1
term2
term3
term4
term5

我想将这些 classed 添加到节点主体 class...

article-term-(term1tid) 
article-term-(term2tid)
article-term-(term3tid) 
article-term-(term4tid)
article-term-(term5tid)

这些是我想更改其 class 名称的页面:

尝试使用template_preprocess_html()

这在您主题的 template.php 文件中:

YOURTHEMENAME_preprocess_html(&$variables) {
  $term_id = arg(1); // For example, or use some &drupal_static() to store a value while preprocessing from module
  $variables['classes_array'][] = 'article-term-' . $term_id;
}

如您所见,您应该先将 template_ 更改为您的 themename_

正如@P1ratRuleZZZ 已经指出的 template_preprocess_html(从您的 sub-theme 的 template.php 文件中实现)是添加正文的函数 类.

问题是,在这个函数中,您需要先加载实际的节点对象,然后获取该术语引用字段的值,最后将它们作为 类 添加到正文标签中。

用你的名字替换 MYTHEMEfield_MYFIELD

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {

  // Get the node.
  if ($node = menu_get_object()) {

    // Check node type.
    if ($node->type === 'article') {

      // Get taxonomy terms.
      $terms = field_get_items('node', $node, 'field_MYFIELD');

      foreach ($terms as $term) {
        // Add body class.
        $variables['classes_array'][] = 'article-term-' . $term['tid'];
      }
    }        
  }
}

leymannx代码真的很完整很好。

但它不包含节点的所有项。

我自己写了这段代码,希望对你有用。

function YOURTHEME_preprocess_html(&$variables) {

    if (arg(0) == 'node' && is_numeric(arg(1))) {
        $node    = node_load(arg(1));
        $results = Whosebug_taxonomy_node_get_terms($node);
        if (is_array($results)) {
            foreach ($results as $item) {
                $variables['classes_array'][] = "article-term-" . $item->tid;
            }
        }
    }

}

有一个名为“"Whosebug_taxonomy_node_get_terms"”的函数,returns 所有术语都附加到一个节点。

function Whosebug_taxonomy_node_get_terms($node, $key = 'tid'){
    static $terms;
    if (!isset($terms[$node->vid][$key])) {
        $query   = db_select('taxonomy_index', 'r');
        $t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
        $v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
        $query->fields($t_alias);
        $query->condition("r.nid", $node->nid);
        $result                  = $query->execute();
        $terms[$node->vid][$key] = array();
        foreach ($result as $term) {
            $terms[$node->vid][$key][$term->$key] = $term;
        }
    }
    return $terms[$node->vid][$key];
}

我希望这段代码是最好的。

将所有这些代码写入您主题的 template.php 文件中。

如果您只希望某些节点具有 class 名称,请添加替换这部分代码。

> if (arg(0) == 'node' && is_numeric(arg(1)) && ( arg(1)==X || arg(1)==Y
> )  ) {