0

What's the best way to add the Parent ID of a page to the <body <?php body_class(); ?>>function?

I am currently using the below function to get the Parent ID of a menu item for a different use; any idea how to get that into the body class?

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;
    }
}

Then printing it in a template like so:

$parentID = get_menu_parent_ID( 'primary' );
0

Using the body_class filter

// 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;
}

Anyway, I recommend you to add some text to the id number, in order to make it more comprehensive, as follows:

// 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;
}

I hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.