Add parent ID to body_class

时间:2015-11-20 作者:CreativeFlair

将页面的父ID添加到<body <?php body_class(); ?>>作用

我目前正在使用以下函数获取菜单项的父ID,以供其他用途;你知道怎么把它带进健美课吗?

function get_menu_parent_ID( $menu_name ) {
    if ( ! isset( $menu_name ) ) {
        return "No menu name provided in arguments";
    }
    $menu_slug  = $menu_name;
    $locations  = get_nav_menu_locations();
    $menu_id    = $locations[$menu_slug];
    $post_id    = get_the_ID();
    $menu_items = wp_get_nav_menu_items( $menu_id );
    $parent_item_id = wp_filter_object_list( 
        $menu_items, array( \'object_id\' => $post_id ), \'and\', \'menu_item_parent\' );
    $parent_item_id = array_shift( $parent_item_id );
    function checkForParent( $parent_item_id, $menu_items ) {
        $parent_post_id = wp_filter_object_list( 
            $menu_items, array( \'ID\' => $parent_item_id ), \'and\', \'object_id\' );
        $parent_item_id = wp_filter_object_list( 
            $menu_items, array( \'ID\' => $parent_item_id ), \'and\', \'menu_item_parent\' );
        $parent_item_id = array_shift( $parent_item_id );
        if ( $parent_item_id == "0" ) {
            $parent_post_id = array_shift( $parent_post_id );
            return $parent_post_id;
        } else {
            return checkForParent( $parent_item_id, $menu_items );
        }
    }
    if ( ! empty( $parent_item_id ) ) {
        return checkForParent( $parent_item_id, $menu_items );
    } else {
        return $post_id;
    }
}
然后在模板中打印,如下所示:

$parentID = get_menu_parent_ID( \'primary\' );

1 个回复
最合适的回答,由SO网友:Capiedge 整理而成

使用body_class 滤器

// Use the filter \'body_class\'
add_filter( \'body_class\', \'parent_id_body_class\' );
function parent_id_body_class( $classes ) {
    // add parent id number to the $classes array
    $classes[] = wp_get_post_parent_id( $post_ID );
    // return the $classes array
    return $classes;
}
无论如何,我建议您在id号中添加一些文字,以便更全面,如下所示:

// Use the filter \'body_class\'
add_filter( \'body_class\', \'parent_id_body_class\' );
function parent_id_body_class( $classes ) {
    // add comprehensive text followed by parent id number to the $classes array
    $classes[] = \'parent-id-\' . wp_get_post_parent_id( $post_ID );
    // return the $classes array
    return $classes;
}
我希望这有帮助。

相关推荐