循环浏览导航项时为foreach()提供的参数无效

时间:2017-09-03 13:53:49

标签: php wordpress

我使用此代码尝试在WordPress中生成自定义导航结构,但我遇到了for循环的问题。 WordPress告诉我$menuitems不是数组:

<?php
  $menu_name = 'main_nav';
  $locations = get_nav_menu_locations();
  $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
  $menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
?>

<nav class="main-navigation col-md-8 col-sm-8">
<ul class="main-nav">
    <?php
    $count = 0;
    $submenu = false;
    foreach( $menuitems as $item ):
        $link = $item->url;
        $title = $item->title;
        // item does not have a parent so menu_item_parent equals 0 (false)
        if ( !$item->menu_item_parent ):
        // save this id for later comparison with sub-menu items
        $parent_id = $item->ID;
    ?>

    <li class="item">
        <a href="<?php echo $link; ?>" class="title">
            <?php echo $title; ?>
        </a>
    <?php endif; ?>

        <?php if ( $parent_id == $item->menu_item_parent ): ?>

            <?php if ( !$submenu ): $submenu = true; ?>
            <ul class="sub-menu">
            <?php endif; ?>

                <li class="item">
                    <a href="<?php echo $link; ?>" class="title"><?php echo $title; ?></a>
                </li>

            <?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id && $submenu ): ?>
            </ul>
            <?php $submenu = false; endif; ?>

        <?php endif; ?>

    <?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id ): ?>
    </li>                           
    <?php $submenu = false; endif; ?>

<?php $count++; endforeach; ?>

</ul>
</nav>

但是我从for循环中得到了Warning: Invalid argument supplied for foreach()

以下是var_dump( $locations )var_dump( $menu )var_dump( $menuitems )的输出:

array(2) {
  ["primary"]=>
  int(15)
  ["menu-1"]=>
  int(15)
}
bool(false)
bool(false)

1 个答案:

答案 0 :(得分:0)

查看上面的var_dump,您的问题似乎源于菜单名称不存在...

$menu_name = 'main_nav';不是存在的菜单名称。

您的var_dump显示存在的菜单名称为:primarymenu-1

$menu_name变量更改为存在的菜单名称。