WordPress custom field info in nav menu?

I’m trying to get custom field info from a page into the nav menu. I’ve had problems with this before… I just don’t “get” the walker menu and how it works.

Basically, In addition to the title of the page, I want to have it output the URL of an image and image description from the custom fields and create a menu item linked to a normal WP page.

Read More

In the nav-menu-template.php file, I’ve tried modifying the start_el function by adding get_post_custom_keys() like this with no success:

$item_output .= '<a'. $attributes .'>';
$item_output .= get_post_custom_values("product_image", $item->ID);
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;

I’ve also tried get_post_meta(); and others with limited success. The best I’ve been able to do is either get one of the images repeating in all the links by specifying a a hard integer value. Or, I’ve been able to get it to output the correct post/page value in text but without an image.

Anyone know of a solution.. what I’m doing wrong?

Related posts

Leave a Reply

1 comment

  1. It would probably be easier to iterate through your nav menu and render it dynamically. The below code will let you iterate through a given nav menu assigned to a nav menu location you would have registered in your functions.php file:

    <ul id="some-menu-id" class="my-fancy-menu">
    <?php
        $menu_name = 'primary';
        if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
            $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
            $menu_items = wp_get_nav_menu_items($menu->term_id);
            foreach ( (array) $menu_items as $key => $menu_item ) {
                // at this point you can get the custom meta from the page
                $image = get_post_meta($menu_item->object_id, '_custom_field_image_url', true);
                $image_description = get_post_meta($menu_item->object_id, '_custom_field_image_description', true);
                // here we are getting the title and URL to the page
                $title = $menu_item->title;
                $url = $menu_item->url;
                $slug = basename($menu_item->url);
                // this allows us to add a current class
                if (basename($_SERVER['REQUEST_URI']) == $slug) { $current = ' current-menu-item'; } else { $current = ''; }
                $menu_list .= '<li class="page-id-'.$menu_item->object_id.$current.'"><a href="' . $url . '">' . $title . '</a><br /><p>'.$image_description.'<br />'.$image.'</p></li>';
            }
        }
        echo $menu_list;
    ?>
    </ul>