Last active
September 13, 2023 14:10
-
-
Save Jehu/978be17391aa035828545caca2367d2b to your computer and use it in GitHub Desktop.
WordPress: set category menu active on post single page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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