3

我需要一个代码来从 Wordpress 中的特殊菜单项中获取父菜单导航项(不是父页面导航项)。

Example: get_parent_menu_nav_item($item->ID)

我在谷歌上花了很多时间解决这个问题,但没有解决方案。

我的菜单的现有代码(例如):

<?php
class MV_Cleaner_Walker_Nav_Menu extends Walker {
    var $tree_type = array( 'post_type', 'taxonomy', 'custom' );
    var $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' );
    function start_lvl(&$output, $depth) {
        $indent = str_repeat("\t", $depth);
        $output .= "\n$indent<ul class=\"sub-menu\">\n";
    }
    function end_lvl(&$output, $depth) {
        $indent = str_repeat("\t", $depth);
        $output .= "$indent</ul>\n";
    }
    function start_el(&$output, $item, $depth, $args) {
        global $wp_query;
        $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
        $class_names = $value = '';
        $classes = empty( $item->classes ) ? array() : (array) $item->classes;
        $classes = in_array( 'current-menu-item', $classes ) ? array( 'current-menu-item' ) : array();
        $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
        $class_names = strlen( trim( $class_names ) ) > 0 ? ' class="' . esc_attr( $class_names ) . '"' : '';
        $id = apply_filters( 'nav_menu_item_id', '', $item, $args );
        $id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : '';
        $output .= $indent . '<li' . $value . $class_names .' id="NEED PARENT ID">';
        $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
        $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
        $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
        $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
        $item_output = $args->before;
        $item_output .= '<a'. $attributes .'>';
        $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
        $item_output .= '</a>';
        $item_output .= $args->after;
        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }
    function end_el(&$output, $item, $depth) {
        $output .= "</li>\n";
    }
}
?>

我希望你能帮助我,非常感谢你的回答。

4

1 回答 1

6

这是一个旧线程,但今天我有一个显示父菜单标题的要求,我使用核心中的一些代码解决了它,只需使用 $item->menu_item_parent 加载元数据,然后使用正确的函数来获取父对象

$object_id = get_post_meta( $item->menu_item_parent, '_menu_item_object_id', true );
$object    = get_post_meta( $item->menu_item_parent, '_menu_item_object',    true );
$type      = get_post_meta( $item->menu_item_parent, '_menu_item_type',      true );

if ( 'post_type' == $type ) {
    $title = get_post( $object_id )->post_title;
} elseif ( 'taxonomy' == $type) {
    $title = get_term( $object_id, $object )->name;
}
于 2016-09-21T13:41:56.477 回答