Adding Class current_page_item

2020-06-18 10:50发布

问题:

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?

回答1:

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>';
    }

}


回答2:

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;
}


回答3:

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>';
   }
}


标签: php wordpress