• pk-71

    (@pauljohnknight)


    I have a situation where if I’m on a single post page for a custom post type, if a custom taxonomy term is present I want to highlight the main nav menu related to that taxonomy term.

    On archive pages this is fairly straight forward because I can use functions like is_tax() for a taxonomy and term, or is_post_type_archive() for a certain post type.

    In the code below how would I add a CSS ‘.page-active’ class to a ‘marketing’ nav menu item when the custom term ‘marketing’ is present in the term list for the page. I am bringing the terms onto the page using get_the_term_list()

    The code for the menu-item is:

    <li class="menu-item menu-item-4"><a title="Marketing" class="td nav-link underline <?php if (is_tax('news_categories','marketing')){echo "page_active";};?>" href="<?php echo esc_url(home_url('/news_categories/marketing'));?>">Marketing</a></li>
    

    The code for showing the term on the custom post type single page is:

    <?php echo get_the_term_list ($post->ID, 'news_categories', ' ', ', ', ''); ?>

    Any ideas how to approach this would be amazing. Also because the menu has a very specific design on mobile it has been hard coded so I’m not using the normal WordPress menu functions.

Viewing 4 replies - 1 through 4 (of 4 total)
  • IF it’s a single post you may be able to check against the global $post object. Since it’s a hard coded menu I’ll leave it to you to add the active class but the conditional could look something like this:

    global $post;
    
    $classes = 'menu-item';
    
    if( has_term( 'term-slug-here', 'taxonomy-here', $post ) ) {
    	$classes .= ' current-menu-item;
    }
    Thread Starter pk-71

    (@pauljohnknight)

    Hi – Would that go in my functions.php file or header.php file?

    Well, you mentioned that the menu was hard coded so since it’s not using the traditional wp_nav_menu() function we won’t have the hooks necessary to add the class from the functions.php file.

    The above code would go into your header and when the list item for your term is displayed you can echo the result:

    <li class="<?php echo esc_attr( $classes ); ?>">

    Thread Starter pk-71

    (@pauljohnknight)

    OK thanks I’ll have a play around. I’m don’t do that much development with WordPress so it is all a bit new.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Add a CSS Class To Menu Item When Custom Taxonomy Term is Present On A Page’ is closed to new replies.