有没有办法可以在wordpress中获取菜单元素的项目,然后用PHP迭代,为每个元素再次获取子菜单元素(如果有的话)?
我想创建一个自定义列表,它让我觉得这比处理the Walker function更容易。
答案 0 :(得分:0)
我发现这个问题已经过时了,但这可能会解决您的问题(以及将来的其他问题):)
if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
$menu_name = 'your-menu-name';
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list = '<ul id="menu-' . $menu_name . '">';
foreach ( (array) $menu_items as $key => $menu_item ) {
$title = $menu_item->title;
$url = $menu_item->url;
if( $menu_item->menu_item_parent == 0){ // Parent
$menu_list .= '<li class="parent"><a href="' . $url . '">' . $title . '</a></li>';
}else{ // Child
$menu_list .= '<li class="child"><a href="' . $url . '">' . $title . '</a></li>';
}
} // END foreach
$menu_list .= '</ul>';
echo $menu_list;
} // END if isset
这将遍历整个菜单,而在循环中,如果有父项或子项,则可以创建if语句。
以下是menu_items
对象中的所有可用数据。
要访问它们,只需在循环中执行此操作:$menu_item->menu_order
。那会给你1
[ID] => 143
[post_author] => 1
[post_date] => 2016-11-22 18:44:19
[post_date_gmt] => 2016-11-22 18:44:19
[post_content] =>
[post_title] => Parent 1
[post_excerpt] =>
[post_status] => publish
[comment_status] => closed
[ping_status] => closed
[post_password] =>
[post_name] => parent-1
[to_ping] =>
[pinged] =>
[post_modified] => 2016-11-22 18:46:19
[post_modified_gmt] => 2016-11-22 18:46:19
[post_content_filtered] =>
[post_parent] => 0
[menu_order] => 1
[post_type] => nav_menu_item
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
[db_id] => 143
[menu_item_parent] => 0
[object_id] => 143
[object] => custom
[type] => custom
[type_label] => Custom Link
[title] => Parent 1
[url] => #
[target] =>
[attr_title] =>
[description] =>
代码来自WordPress文档,您可以在那里阅读更多内容:wp_get_nav_menu_items