最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp_nav_menu_items for one menu

programmeradmin1浏览0评论

I tested this tutorial. It works great.

The problem is that in the tutorial there is one menu while I have 2 menus. Let me know how I can customize this function for the feature only applies to primary menu.

The code :

function new_nav_menu_items($items) {
    $items = "";
    $args = array(
        "post_type" => "page", 
        "order"     => "ASC", 
        "orderby"   => "menu_order"
    );
    $the_query = new WP_Query($args);

    if($the_query->have_posts()):
        while($the_query->have_posts()):
            $the_query->the_post();
                $items .= '<li><a href="#post-'. get_the_ID() .'">' . get_the_title() . '</a></li>';           
        endwhile;
    else:
        echo "";
    endif;

    return $items; 
}

add_filter("wp_nav_menu_items", "new_nav_menu_items");

I tried with if( $args->theme_location == 'primary' ) but I do not know how to use it .. I can not apply this one

I tested this tutorial. It works great.

The problem is that in the tutorial there is one menu while I have 2 menus. Let me know how I can customize this function for the feature only applies to primary menu.

The code :

function new_nav_menu_items($items) {
    $items = "";
    $args = array(
        "post_type" => "page", 
        "order"     => "ASC", 
        "orderby"   => "menu_order"
    );
    $the_query = new WP_Query($args);

    if($the_query->have_posts()):
        while($the_query->have_posts()):
            $the_query->the_post();
                $items .= '<li><a href="#post-'. get_the_ID() .'">' . get_the_title() . '</a></li>';           
        endwhile;
    else:
        echo "";
    endif;

    return $items; 
}

add_filter("wp_nav_menu_items", "new_nav_menu_items");

I tried with if( $args->theme_location == 'primary' ) but I do not know how to use it .. I can not apply this one

Share Improve this question edited Apr 13, 2017 at 12:37 CommunityBot 1 asked Sep 21, 2015 at 10:04 orèliorèli 12 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

I came across your question by looking for an answer myself. Here is how I made the code work for me:

function new_nav_menu_items( $items, $args ) {
    if ( $args->menu == 'primary' ) {
        $items = "";
        $args = array(
            "post_type" => "page", 
            "order"     => "ASC", 
            "orderby"   => "menu_order"
        );
        $the_query = new WP_Query( $args );
        if ( $the_query->have_posts() ):
            while( $the_query->have_posts() ): 
                $the_query->the_post();
                $items .= '<li><a href="#post-' . get_the_ID() . '">' . 
                    get_the_title() . '</a></li>';
            endwhile;
        else:
            echo "";
        endif;
    } 
    return $items; 
}
add_filter( "wp_nav_menu_items", "new_nav_menu_items" );

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论