campatsky
campatsky

Reputation: 324

wp_nav_menu only show the first 5 menu items

How do I limit the number of menu items pulled in by wp_nav_menu? I only want to pull in the first 5 menu items even though there are 20 in the actual menu. The client will select the order and in all other places it's fine to have the full menu appear.

Here's what I'm trying but it doesn't seem to work :'-(

wp_nav_menu( array( 'theme_location' => 'quicklinks', 'menu_item_start' => 1, 'menu_item_end' => 5) );

Upvotes: 1

Views: 2328

Answers (4)

Jawad Abdani
Jawad Abdani

Reputation: 11

Try adding this code to your theme's functions.php file.

function limit_quicklinks_menu_items( $items, $args ) {
        if ( $args->theme_location == 'quicklinks' ) {
            $items = array_slice( $items, 0, 5 );
        }
        return $items;
    }

add_filter( 'wp_nav_menu_items', 'limit_quicklinks_menu_items', 10, 2 );

This code can be used to limit the number of menu items pulled in by wp_nav_menu() for a specific menu location, such as quicklinks. The code uses the wp_nav_menu_items filter to modify the menu items array before it's displayed.

Upvotes: 0

Gildas.Tambo
Gildas.Tambo

Reputation: 22643

You can use css :nth-child() , in your case that would be (n+6)

nav.main-navigation li:nth-child(n+6){
    display: none;
}

Upvotes: 0

Nic Bug
Nic Bug

Reputation: 391

this is my solution which works (you need to modify "primary_navigation"):

function max_nav_items($sorted_menu_items, $args){
    if($args->theme_location != "primary_navigation") return $sorted_menu_items;
    $items = array();
    foreach($sorted_menu_items as $item){
        if($item->menu_item_parent != 0) continue;
        $items[] = $item;
    }
    $items = array_slice($items,0,8);
    foreach($sorted_menu_items as $key=>$one_item){
        if($one_item->menu_item_parent == 0 && !in_array($one_item,$items)){
            unset($sorted_menu_items[$key]);
        }
    }
    return $sorted_menu_items;
}
add_filter("wp_nav_menu_objects","max_nav_items",10,2);

Upvotes: 0

LindaJeanne
LindaJeanne

Reputation: 214

Could you create a seperate menu in admin, with just those five items, in the order that the client wants them? Then you could attatch that menu to this location, and the other to the others.

Upvotes: 1

Related Questions