0

I am working on my first WordPress custom theme and I now have a problem. I've organized the site such that I'm using a front-page.php as my home page that shows a long page with some links. These links go to other Pages. Let's call these T1s.

On those pages, I have a long page body of content. I want to make some of those links go to Posts (Let's call these T2s) that have a category with the same slug as their parent Page.

The problem is that I don't know how to highlight the correct nav when viewing those Posts.

Somehow I need to look at the current post, grab its category and see if it matches the url slug of an item in the Nav and highlight that nav item.

Is this a custom filter?

I see that this happens automatically if I make the T2s be Pages, instead of Posts, and then set the parent/child relationship, accordingly. But then all site content will have to be Pages, with a fixed hierarchy. I wouldn't be using Posts at all.

I've also seen that if I make the Nav item be a Category that it'll happen automatically as well. However, I don't like the /category/ in the url.

I guess I need to figure out how to make a post's category match a page's slug in some filter?

Is that the best approach?

Thanks.

0

Well, once I got debugging working, I was able to figure out how this nav_menu_css_class filter works.

First, I parse the url off of the nav item. Then I use that to compare against the post's category array. If I find a match, I set the $classes[] array, and I'm good to go.

I know parsing the url is a bit ghetto, but I was hoping that the $item would be the target page, but it's not. It's just the post that's created to be in the nav. There is not handle to its target other then the url.

add_filter('nav_menu_css_class', 'post_current_category_class', 10, 2);

function post_current_category_class($classes, $item) {

    // $classes is the list of classes on a nav item
    // $item is the nav item

    if ( is_singular('post') ) {

        $navUrl = $item->url;
        $navParts = parse_url($navUrl);
        $location = ltrim($navParts['path'], '/');
        $location = rtrim($location, '/');

        $post_category_ids = wp_get_post_categories( $GLOBALS['post']->ID);
        $categories = array();

        foreach($post_category_ids as $c){
            $cat = get_category( $c );
            $categories[] = $cat->slug;
        }

        if (in_array($location, $categories)){
            $classes[] = 'current-menu-item';
        }

    }

    return $classes;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.