PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 20, 2022

[FIXED] Custom post type active menu item

 January 20, 2022     custom-post-type, php, wordpress     No comments   

Issue

I created a custom post type called “team" and added the link to the archive page to the WP menu. Once user clicks on it, he is shown all team members and that current page is highlighted in the menu. But when i click on individual team member, his page opens and the “Team” in the menu isn’t highlighted anymore, and it should be.

This is how it shows up when the team page is opened:

<li id="menu-item-17" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item active”>
<a href="http://localhost:8888/site/team/">Team</a>
</li>

and this is what i get in the menu when i open individual member page:

<li id="menu-item-17" class="menu-item menu-item-type-custom menu-item-object-custom”>
<a href="http://localhost:8888/site/team/">Team</a>
</li>

Since I’m not a PHP developer, i don’t have any idea on how to make it work, any suggestion would be highly appreciated :)


Solution

I got this to work for me, taken and edited from, here. Where I have 'bonsai' change it to your custom post type. Where I have put 'menu-item-299', change it to the id of your menu item that you want to keep highlighted.

function change_page_menu_classes($menu)
{
    global $post;
    if (get_post_type($post) == 'bonsai')
    {
        $menu = str_replace( 'current-menu-item', '', $menu ); // remove all current_page_parent classes
        $menu = str_replace( 'menu-item-299', 'menu-item-299 current-menu-item', $menu ); // add the current_page_parent class to the page you want
    }
    return $menu;
}
add_filter( 'nav_menu_css_class', 'change_page_menu_classes', 10,2 );

Let me know if you have issues, cos maybe they affect me to :)



Answered By - Gavin Simpson
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing