francky
francky

Reputation: 15

How to limit the search level in the Drupal taxonomy?

​ I created taxonomy terms and subterms. My nodes can be associated with only one term.

Here is my taxonomy:

enter image description here

I created a view block that displays sticky nodes. I added to my view the contextual filter "Configure contextual filter: Content: Has taxonomy term identifier (with depth)", with the following settings :

enter image description here

I want the view block to appear only on the pages associated with a term, its sub-terms, its parents, its siblings. Up to a certain level.

Here is an example :

If the sticky node is associated with Wallet, it must appear in the view block, on the nodes associated with:

It must therefore appear on all Crypto nodes and its sub-terms.

I don't know what the level of the term Crypto is, but the module below should only search up to that level :

<?php

use Drupal\views\ViewExecutable;
use Drupal\node\NodeInterface;

/**
 * Implements hook_views_pre_view().
 */
function sticky_content_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() !== 'sticky_content' || $display_id !== 'block_1') {
    return;
  }
  $node = \Drupal::routeMatch()->getParameter('node');
  if (!$node instanceof NodeInterface) {
    return;
  } 
  $tid = $node->field_tags->target_id;
  $parents = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadAllParents($tid);
  $args[0] = $parents ? array_key_last($parents) : $tid;
}

I don't know what to change in this part of the code, to make the custom module stop looking for it at some level. Currently it searches down to the last parent term. I want it to search up to the penultimate parent term :

  $tid = $node->field_tags->target_id;
  $parents = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadAllParents($tid);
  $args[0] = $parents ? array_key_last($parents) : $tid;

Upvotes: 0

Views: 624

Answers (1)

Thomas Lefetz
Thomas Lefetz

Reputation: 154

You can use this method :

// Load the taxonomy tree with special parameters. 
$tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree( 
  'some_vocabulary', // This is your taxonomy term vocabulary (machine name). 
  0, // This is "tid" of parent. Set "0" to get all. 
  1, // Get only 1st level. 
  TRUE // Get full load of taxonomy term entity. 
);

You will be allowed to load the level you want.

EDIT:

In your case, it will be :

// Load the taxonomy tree with special parameters. 
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree( 
  'tags', // This is your taxonomy term vocabulary (machine name). 
  0, // This is "tid" of parent. Set "0" to get all. 
  1, // Get only 1st level. 
  TRUE // Get full load of taxonomy term entity. 
);

foreach ($terms as $term) {
 $term_data[] = array(
   'id' => $term->tid,
   'name' => $term->name
 );
}

I thought the comments were clear enough.

Upvotes: 0

Related Questions