Skip Navigation

[Resolved] Add current class to menu item

This support ticket is created 5 years, 5 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Hong_Kong (GMT+08:00)

This topic contains 4 replies, has 2 voices.

Last updated by hugoC-5 5 years, 4 months ago.

Assisted by: Luo Yang.

Author
Posts
#1349859
Schermafbeelding 2019-09-27 om 10.07.01.png

I have a page containing a view that displays the posts in a certain category. I would like to keep the menu item of this page active if I click through to one of these posts (see screenshot).

I looked at post relationships but this doesn't seem to solve my problem.

I guess I would need a way to add a class "current" or "active" to the "programma" menu item when I visit a post belonging to this view.

#1349873

Hello,

As I mentioned in the chat:
There isn't such kind of built-in feature within Toolset plugins, you might consider custom codes, for example, use WordPress filter hook nav_menu_css_class to trigger a PHP function, check if current post/page is belonging to that specific view, then add the CSS class name

More help:
https://developer.wordpress.org/reference/hooks/nav_menu_css_class/

If you need assistance for it, please provide a test site with the same problem, fill below private message box with login details and FTP access, also point out the problem page/post URL and view URL, I can try to setup a demo for you. thanks

#1351277

Thanks for the details, I can log into your website, will update here if there is anything found

#1351287

I assume we are talking about the post view "Programma" (id 691) and the menu item "Programma" (ID 694).

I have done below modifications in your website:
1) Edit the post view "Programma" (id 691) :
Disable option: Don't include current page in query result

2) Dashboard-> Toolset-> Settings-> Custom Code
Add a file "add_current_class", with below codes:

add_filter( 'nav_menu_css_class' , function( $classes, $item, $args, $depth ) {
 
    if($item->ID == 694){
    	$post_id = get_the_ID();
      	$view_results = get_view_query_results( 691 );
      	foreach($view_results as $result){
        	if($result->ID == $post_id){
            	$classes[] = 'current_page_item current-menu-item active';
              break;
            }
        }
    }
 
    return $classes;
} , 10, 4 );

Please test again, check if it is what you want. thanks

#1357917

It works like a charm. Thanks a lot!