Add class to log1x/navi when on single custom post type

I’m using log1x/navi to build my primary navigation.

I’m using a custom template to show custom post types and I would like to add an “active” class to the menu item when I’m on the single page for that custom post type. Since it’s a custom template, it does not know about any parent pages or archive pages.

How would I best approach this?

public function navigation(){
        $navigation = (new Navi())->build('primary_navigation');

        if($navigation->isEmpty()){
            return;
        }

        if(is_singular('recipe')){
            // I'm guessing I should be able to add a custom class here?
        }

        return $navigation->toArray();
    }

Thanks in advance!

Kind regards

Have you checked out the examples section in the Navi docs? This page should give you an idea about how to add an “active” class based on a condition.

2 Likes

Hi csorrentino!
Thanks for your reply. I have checked out the docs. The active item is working, but when I’m in a custom post type, the builder doesn’t know about the parent page because it is a custom template.

The structure is as follows: I have a custom page template “Recipes”, which is in the menu and does show as active item when I’m on the page. That page has a list of custom post types “recipe”. When I click an item and go to the single template, I would like the menu to still be active, since you’re actually still on some sort of “Recipes” page. The menu doesn’t know that it’s on a child page there.

I hope it’s clear what I’m trying to do.

Kind regards
Jonas

Ok, this is untested but you could try changing the <li> code to something like this:
<li class="menu-item {{ $item->classes ?? '' }} {{ $item->active || (is_singular() && $item->url == get_post_type_archive_link(get_post_type())) ? 'active' : '' }} ">

Part of that is indeed what I had to set the normal active class on the page. But this doesn’t help for keeping the menu item active when on a single post. The archive link is unknown since it’s not an archive page. It’s a custom template, that’s why it’s not working properly.

ok, it seems like you just need check for is_singular(‘recipe’) or whatever your post type is called:

<li class="menu-item {{ $item->classes ?? '' }} {{ $item->active || (is_singular('recipe')) ? 'active' : '' }} ">