Skip to content

Instantly share code, notes, and snippets.

@Jehu
Last active September 13, 2023 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jehu/978be17391aa035828545caca2367d2b to your computer and use it in GitHub Desktop.
Save Jehu/978be17391aa035828545caca2367d2b to your computer and use it in GitHub Desktop.
WordPress: set category menu active on post single page
<?php
/**
* helper function to test if post is in subcategory
*/
if (!function_exists("mwe_is_in_subcategory")) {
function mwe_is_in_subcategory($categories, $_post = null)
{
foreach ((array) $categories as $category) {
$subcats = get_term_children((int) $category, "category");
if ($subcats && in_category($subcats, $_post)) {
return true;
}
}
return false;
}
}
/**
* Set menu active css classes of categories
* Example for CPT "produkt"
*/
add_action("nav_menu_css_class", "add_current_nav_class", 10, 2);
function add_current_nav_class($classes, $item)
{
// Getting the current post details
$post = get_queried_object();
if ($item->object == "category" && $post->post_type == "produkt") {
// is the post in a subcategory of this category?
if (mwe_is_in_subcategory($item->object_id)) {
$classes[] = "current-menu-parent";
}
// is post in this category?
if (in_category($item->object_id, $post)) {
$classes[] = "current-menu-item";
}
}
// Return the corrected set of classes to be added to the menu item
return array_unique($classes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment