1

I am trying to create some sort of custom menu. Where I list all titles of my pages in the main menu and display the value of a meta box of each of these pages. For some reason the get_post_meta remains empty for all items. I fail to see why.

<?php
 $array_menu = wp_get_nav_menu_items('header-menu');
    $menu = array();
    foreach ($array_menu as $m) {
        if (empty($m->menu_item_parent)) {
             ?>
             <h4><a href="<?php echo $m->url;?>"><?php echo $m->title;?></a></h4>
             <p>
                <?php echo get_post_meta($m->ID, 'meta_box_subtitle', true); ?>
             </p>
<?php       
        }
    }
?>
  • the titles are returning normal? – David Lee Feb 20 '17 at 20:32
  • Why do you need global $wp_query;? – TrubinE Feb 20 '17 at 20:38
  • Yes, they are. The ID's are correct aswell. And I can succesfully get the post_meta of the $post->ID on this page. – woony Feb 20 '17 at 20:39
  • The global is a remainder of things I have tried, I should remove that here. – woony Feb 20 '17 at 20:39
2

You are sending the ID of the menu item not the ID of the page try using url_to_postid() like this:

<?php
 $array_menu = wp_get_nav_menu_items('header-menu');
    $menu = array();
    foreach ($array_menu as $m) {
        if (empty($m->menu_item_parent)) {
             ?>
             <h4><a href="<?php echo $m->url;?>"><?php echo $m->title;?></a></h4>
             <p>
                <?php global $wp_query;
                 $pageID = url_to_postid( $m->url );  
                 echo get_post_meta($pageID, 'meta_box_subtitle', true); 
                ?>
             </p>
<?php       
        }
    }
?>
  • Ofcourse! I guess it is getting late :p Thanks a lot for the insight! Your solution works. – woony Feb 20 '17 at 20:41

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.