drgc9632 2015-12-04 18:46
浏览 59

如何确定wordpress菜单项是否处于活动状态?

I'm using Wordpress to create menus and I'm trying to use the object_id to determine whether or not the menu item is active. The problem is that when I set the menu-item-object-id manually, it is overridden by it's own ID.

I have a function that creates the menu and then another that adds menu items to each menu:

function create_menu($menu) {

    foreach($item in $key => $menu['items']) {
        create_menu_item($item, $key, $menu['id']);
    }
}

function create_menu_item($item, $position, $menuID) {

    // i'll use a dynamic value for the object id, but not even hard coding it works
    $args = [
        'menu-item-position' => $position,
        'menu-item-title' =>  (isset($item['title'])) ? $item['title'] : null,
        'menu-item-classes' => (isset($item['classes'])) ? $item['classes'] : null,
        'menu-item-url' => (isset($item['url'])) ? $item['url'] : null,
        'menu-item-status' => (isset($item['status'])) ? $item['status'] : 'publish',
        'menu-item-parent-id' => (isset($item['parent'])) ? $item['parent'] : 0,
        'menu-item-object-id' => '5'
    ];

    wp_update_nav_menu_item($menuID, 0, $args);
}

Everything seems to be working as expected except for the menu-item-object-id property! I manually set it be object's ID but when I use wp_get_nav_menu_items() the $post->object_id is always the same as it's own ID, $post->ID.

function get_menu() {

    global $post;

    $menu = wp_get_nav_menu_items('primary');

    foreach($menu as $item) {

        // $item->object_id should now be '5' but instead it is equal to $item->ID so I am unable to check if it's active

        if($item->object_id == $post->ID) {
            // item is active
        }
    }

    return $menu;
}

Why is my menu-item-object-id property being overwritten?

  • 写回答

1条回答 默认 最新

  • doufan6544 2015-12-10 18:55
    关注

    It's really not intuitive or documented anywhere, but the solution was to set post_type as the menu-item-type and menu-item-object to page.

    $args['menu-item-type'] = 'post_type';
    $args['menu-item-object'] = 'page';
    $args['menu-item-object-id'] = $page->ID;
    

    Once you have those properties set, setting menu-item-url becomes unnecessary. Wordpress will automatically set the url using the page permalink.

    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?