0

I set css class for menu items.

I want to get css class of current menu item and set it to body tag.

What should i do ?

2
  • You can identify the current menu item by doing a .hasClass('current-menu-item') in jQuery... but what are you trying to do with it? I'm not clear. Commented Oct 10, 2013 at 7:32
  • Ex: I want change background base on menu items. So i need to add class of menu item to body. I do not want to use javascript, i want to do it with PHP
    – Chameron
    Commented Oct 10, 2013 at 7:53

2 Answers 2

0

You're going about this backwards. What you want to do is use jQuery to test for the presence of the current menu class, then see if that item has the assigned class. If it does, then you add your CSS to the body.

<script type="text/javascript">
    jQuery(document).ready(function($) {
        if($('li.current-menu-item').hasClass('your_custom_class')) {
            $('body').css('background-color', 'orange');
        }
    });
</script>

Integrating my comment... you probably want to cache the selector then loop through a few more times.

<script type="text/javascript">
    jQuery(document).ready(function($) {
        var menuitem = $('li.current-menu-item');
        if (menuitem.hasClass('your_custom_class')) {
            $('body').css({
                'background-color': 'orange',
                'background-image': 'url(http://someurl.com/thatimage.jpg'
            });
        }
        else if(menuitem.hasClass('your_custom_class')) {
            $('body').css({
                'background-color': 'orange',
                'background-image': 'url(http://someurl.com/thatimage.jpg'
            });
        }
    });
</script>
3
  • You should be able to add more CSS options using the .css({}) syntax, then loop through your other classes using elseif/elseif/elseif/else. You should probably cache $('li.current-menu-item') as well, since you'll be looping over it multiple times. Commented Oct 10, 2013 at 8:08
  • thank you, but i do not want to use javascript. I want to do it with PHP only
    – Chameron
    Commented Oct 10, 2013 at 8:12
  • Ok, have fun with that Commented Oct 10, 2013 at 8:18
0

'wp_get_nav_menu_items' by using this function you can get the menu items & associated pages/posts with it.

Below is the example

custom_menu_slug is the slug of menu.(theme location)

 $menu_name = 'custom_menu_slug';
    $menu = wp_get_nav_menu_object( 'custom_menu_slug' ); // get Menu ID from menu slug
    $menu_items = wp_get_nav_menu_items($menu->term_id); // $menu->term_id=Menu Id
    foreach ( (array) $menu_items as $key => $menu_item ) {
      if($menu_item->object_id==current_page_id){ // Your current page id 
      echo  $class = $menu_item->classes[0];
      }

    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.