We help IT Professionals succeed at work.

Wordpress menu

stargateatlantis
on
Lets say you have the following menu structure below

Home
Weddings
Engagements
Contact

The menu name is called custom

Now what I am trying to figure out is how to get the childs from Weddings and the childs from Engagements without having to add them to the menu manually in the menu designer.

Both Weddings and Engagements are parents.
Comment
Watch Question

The code below will loop through and output the posts under wedding. Is this what you were looking for?

Function references:
http://codex.wordpress.org/Function_Reference/get_cat_ID
http://codex.wordpress.org/Template_Tags/get_posts
$catID = get_cat_ID("Weddings");
$posts = get_posts(array( 'category' => $catID, 'orderby' => $orderby, 'order' => $order, 'post_status' => 'publish', 'numberposts' => 1000 ));
if ($posts) {
	foreach($posts as $loop) {
		$category = get_the_category($loop->ID);
		if ($category[0]->cat_ID == $catID) {
			$output .= '<li><a ';
			if($post_id==$loop->ID) { $output .= 'style="color:red;" '; }
			$output .= 'href="'.get_permalink($loop->ID).'">'.$loop->post_title.'</a></li>';
		}
	}
}

Open in new window

Author

Commented:
is there a way you can do this using just wp_nav_menu function ?
You could use wp_get_nav_menu_items to grab the main menu elements and then loop through them.

http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items

Below is some code and here is a reference of it working: http://www.matthewstevenkelly.com/blog/uncategorized/menu-test.html

This would require you manually adding in the id's etc.
$menu_name = 'Test';
$menu_items = wp_get_nav_menu_items($menu_name);
$menu_list = '<ul id="menu-' . $menu_name . '">';

foreach ( (array) $menu_items as $key => $menu_item ) {
  $title = $menu_item->title;
  $url = $menu_item->url;
  $menu_list .= '<li><a href="' . $url . '">' . $title . '</a>';
  $catID = get_cat_ID($title);
  if($catID>0) {
   $posts = get_posts(array( 'category' => $catID, 'post_status' => 'publish', 'numberposts' => 1000 ));
   if ($posts) {
     $menu_list .= '<ul>';
     foreach($posts as $loop) {
         $menu_list .= '<li><a href="'.get_permalink($loop->ID).'">'.$loop->post_title.'</a></li>';
     }	
     $menu_list .= '</ul>';
   }
  }
  $menu_list .= '</li>';
}
$menu_list .= '</ul>';

echo $menu_list;

Open in new window

Author

Commented:
Great code but the only problem is that it doesn't include all the default wordpress css code in it.  It doesn't have

class="menu-item menu-item-type-post_type menu-item-object-page"

Open in new window

Unfortunately, those would have to be added in to the code.

I don't think there is any other way to do what you are trying to do. You may have to add the posts to the menu manually, instead of automatically, if that is an option for you.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.