7 SHARES

Display content based on WordPress navigation menu

WordPress, function, menu, navigation, content

For one page WordPress theme I needed to display content based on defined menu. So I had menu location named top_menu and my job was to find what pages are inside and to display their content. First I needed to use function that would bring me back name of menu assigned to that location. And thanks to this wordpress.stackexchange.com I find that function.

function valeka_menu_name( $theme_location ) {
    if( ! $theme_location ) return false;
   
    $theme_locations = get_nav_menu_locations();
    if( ! isset( $theme_locations[$theme_location] ) ) return false;
   
    $menu_obj = get_term( $theme_locations[$theme_location], 'nav_menu' );
    if( ! $menu_obj ) $menu_obj = false;
    if( ! isset( $menu_obj->name ) ) return false;
   
    return $menu_obj->name;
}

Once I wrote that function I need to use it for menu location  top_menu. But first we need to get all theme locations and to check are they empty. Using !isset was not good idea as there would be mess if user remove menu from that location. Then we apply this function valeka_menu_name and we get all pages from that menu.

After checking if menu has any pages, we take what we need and in my case it was only page title and content. I wrapped content into article and using foreach loop displayed content for all pages from navigation.

And this is how final code looks like:

<?php  if ( ( $theme_locations = get_nav_menu_locations() ) && !empty( $theme_locations['top_menu'] ) ) {

$nav_name = valeka_menu_name('top_menu');	 
$menuItems = wp_get_nav_menu_items($nav_name);

if (!empty($nav_name)) {
  foreach($menuItems as $page) {
  
    $post = get_post($page->object_id);
    $title = $page->title;
    $content = apply_filters('the_content', $post->post_content);  ?>
    
    <article>
      <h2 class="title"><?php echo ($title); ?></h2>
      <div class="content">
        <?php echo $content;  ?>		
      </div>						
    </article>
    
<?php }
   }
} ?>

 

So let me know if this code worked well for you or if you have any suggestions how to write this code better.

Share on Facebook7Share on Google+0Tweet about this on Twitter