Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Class current_page_item

Tags:

php

wordpress

I am working on a Wordpress-Design and i want to creat a Custom Menu.

$items = wp_get_nav_menu_items('Menu', array(
    'order'                  => 'ASC',
    'orderby'                => 'menu_order',
    'post_type'              => 'nav_menu_item',
    'post_status'            => 'publish',
    'output'                 => ARRAY_A,
    'output_key'             => 'menu_order',
    'nopaging'               => true,
    'update_post_term_cache' => false));
echo '<pre>'; print_r($items); echo '</pre>'; 
foreach($items as $item){
    echo '<div class="menu_entry"><a href="'.$item->url.'">'.$item->title.'</a></div>';
}

The problem is, i need the "current-page"-Class, which is WordPress creating - in the Standard Menu.

Any Ideas how to add this class?

like image 318
Styler2go Avatar asked Apr 04 '12 21:04

Styler2go


3 Answers

Solution time:

WordPress's function that adds these classes is _wp_menu_item_classes_by_context(). This is called already when you use wp_nav_menu but not wp_get_nav_menu_items. Fortunately, the latter provides a filter so we can do it ourselves:

add_filter( 'wp_get_nav_menu_items', 'prefix_nav_menu_classes', 10, 3 );

function prefix_nav_menu_classes($items, $menu, $args) {
    _wp_menu_item_classes_by_context($items);
    return $items;
}
like image 64
Ethan C Avatar answered Oct 20 '22 11:10

Ethan C


You can do a compare on the current page / cat etc ID against the menu items object_id which is the ID of the page / category etc its linked to.

Something like (untested);

global $post;
$thePostID = $post->ID;
foreach($items as $item){

    if($thePostID === $item->object_id) {
        echo '<div class="menu_entry"><a href="'.$item->url.'" class="current-menu-item">'.$item->title.'</a></div>';
    }else{
        echo '<div class="menu_entry"><a href="'.$item->url.'">'.$item->title.'</a></div>';
    }

}
like image 44
noponies Avatar answered Oct 20 '22 11:10

noponies


Using the function get_queried_object_id(). This works fine in all the pages, including the Blog page.

See an example:

if ( $menu_items = wp_get_nav_menu_items( 'menu' ) ) {
   foreach ( $menu_items as $menu_item ) {
      $current = ( $menu_item->object_id == get_queried_object_id() ) ? 'current' : '';
      echo '<li class="' . $current . '"><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>';
   }
}
like image 31
Gabriel Stafoca Avatar answered Oct 20 '22 09:10

Gabriel Stafoca