1
votes

Entirely Revised Please Reread

Hello, The theme I am using displays the page's title as opposed to it's menu label in the breadcrumbs. I am trying to get the breadcrumbs to instead display the associated menu label if it is available and if not then default to the page_title.

I have come up with some code that I think is close. Line 4/// $menu_items = wp_get_nav_menu_items( $slug ); returns null and it should return the nav item that contains $slug of the current post. Obviously, there is something I do not understand.

What I am attempting to do is get the slug of the current post, then using the slug get the nav item post. Then extract the title of the nav item and use that in place of the page title in the breadcrumbs. If the page was not in the nav system then it should default to the page title, as might be the case for a ppc campaign landing page.

if ( is_page() && !$post->post_parent ) {
    $title = null;
    $slug = mpactMEDIA_get_the_slug( get_the_ID() );
    $menu_items = wp_get_nav_menu_items( $slug );
    //var_dump((array)$menu_items);
    foreach ( (array)$menu_items as $key => $menu_item ) {
    $title = $menu_item->post_title;
    }
    if ( $title ) { echo $delimiter . ' ' . $before . $title . $after; }
    else { echo $delimiter . ' ' . $before . get_the_title() . $after; }
}

I'm my functions.php file I have the following function

function mpactMEDIA_get_the_slug( $id=null ){
    if( empty($id) ) global $post;
    if( empty($post) ) return '';
        $id = $post->ID;
    endif;
    $slug = basename( get_permalink($id) );
    return $slug;
}

Thank you in advance,

Tim

2
Can you reduce this giant function to only the part you're interested?brasofilo
Not a problem Brasfilo. I've edited the post and tried to clarify my query a bit. Thank you.STEAMworks Learning Center

2 Answers

4
votes

I read the question a few times, I got here searching for an answer, ended up making my own.

function get_menu_label_by_post_id($post_id, $menu) {

    $menu_title = '';
    $nav = wp_get_nav_menu_items($menu);

    foreach ( $nav as $item ) {

        if ( $post_id == $item->object_id ) {
            $menu_title = $item->post_title;
            break;
        }

    }

    return ($menu_title !== '') ? $menu_title : get_the_title($post_id);

}

Example usage:

echo get_menu_label_by_post_id($post->ID, 'Primary Nav');

This will return what the menu label is if it finds it, otherwise just the title of the post ID.

0
votes

Check the documentation for wp_get_nav_menu_items. It doesn't take a page slug as a parameter at all.

If you want to list child pages of a given page, use wp_list_pages and pass a child_of parameter to it.

Also, as a side note, if you know the $post and want the slug, it's just $post->post_name