Set blog archive to active when browsing archive

I have a link to my blog archive in my main menu. When the user clicks it and the blog is displayed (on /blog/ – I have a static front-page) the link receives the “current” class (or whatever the name is). When the user clicks on a blog post the blog link in the menu still has the “current” class (or current-page-parent or similar).

This is all good. However, when the user clicks on one of the blog categories the blog link no longer has the “current” class (or any of the parent classes – IE it’s impossible to style it as selected).

This is not only true for the normal blog archive but also for any custom post type archives with custom taxonomies.

What I would like is that the blog link still has the active class. Even when browsing blog categories, tags or perhaps even dates.

Is there any non-hackish way of solving this?

1 Answer
1

Ok so this is how I ended up solving it. Please note it’s not exactly super tested but it seems to work at least. Also, if you’re not using a static front-page it may require some changes (get_option(‘page_for_posts’) notably).

Also note that I’m using “active-parent” as my class name. This is because I’m also using Roots’ menu cleanup code which replaces all the “current_page”-classes with “active”, “active-parent” and “active-ancestor”. You might wanna use the “official” WP-class names instead.

<?php
add_filter('nav_menu_css_class', 'sleek_active_archive_link_on_taxonomies', 10, 2);

function sleek_active_archive_link_on_taxonomies ($cssClasses, $item) {
    global $wp_query;

    # Only do this on archive pages
    if (is_archive()) {
        # This is the link to the blog archive
        if ($item->object_id == get_option('page_for_posts')) {
            # If we're on a blog archive - give the blog link the active class
            if (is_category() or is_tag() or is_day() or is_month() or is_year()) {
                $cssClasses[] = 'active-parent';
            }
        }
        # This is a link to a custom post type archive
        elseif ($item->type == 'post_type_archive') {
            # If we're on a taxonomy and this post type has that taxonomy - make it look active
            if (is_tax()) {
                global $wp_taxonomies;

                $term = $wp_query->get_queried_object();

                if (isset($wp_taxonomies[$term->taxonomy])) {
                    if (in_array($item->object, $wp_taxonomies[$term->taxonomy]->object_type)) {
                        $cssClasses[] = 'active-parent';
                    }
                }
            }
        }
    }

    return $cssClasses;
}
?>

Leave a Comment