James
James

Reputation: 737

Method for modifying nav menu based on custom taxonomy archive page

I have a navigation menu which is produced from a custom taxonomy in wordpress. The menu displays the parent, first child and second child by default. For example:

Filmmaking > Production > Cinematography

If a user selects the second child Cinematography I want the page to change and with it the navigation menu to update. On the new page I want it show the second child and the additional children under, for example.

Cinematography > Lenses
               > Cameras
               > Lighting

I have written the code yet but trying to get the correct approach. What is the best method for setting the menu to the correct point? I figure I could use a couple of options;

  1. Use the page URL which has the current taxonomy term in it and determine the rest of the menu from this?

  2. Store some kind of value in the session storage to determine the term clicked when they click the menu item and set the new menu from this

Is this the correct way to approach this or is there a better way?

Upvotes: 0

Views: 141

Answers (1)

Cadu De Castro Alves
Cadu De Castro Alves

Reputation: 647

You should use get_queried_object to get the current term ID:

$term_id = get_queried_object()->term_id;

Then, you can use get_term_children to construct the menu based on the parent one:

$taxonomy_name = 'taxonomy_name';
$term_children = get_term_children($term_id, $taxonomy_name);

Obs.: Replace taxonomy_name with your custom taxonomy name.

get_term_children usually returns an array with its children's IDs:

array(4) {
  [0]=> int(10)
  [1]=> int(20)
  [2]=> int(30)
  [3]=> int(34)
}

Finally, you can generate the custom menu:

<ul>
  <li>Cinematography
    <ul>
      <?php 
        foreach($term_children as $child_id) :
          $term = get_term_by('id', $child_id, $taxonomy_name); 
      ?>
      <li>
        <a href="<?php echo get_term_link($child_id, $taxonomy_name); ?>">
          <?php echo $term->name; ?>
        </a>
      </li>
      <?php endforeach; ?>
    </ul>
  </li>
</ul>

Upvotes: 1

Related Questions