0

is there any way to setup wordpress so that when I create a CPT and then have a menu item (preferably the archive page) that will automatically create a dropdown of all the actual posts and the links will be to the CPT single pages?

so for instance if i had stores as my CPT the menu would look like this:

Stores (to archive page)

  • location 1(to location 1 single)

  • location 2(to location 2 single)

  • location 3(to location 3 single)

and then if i add a new store location a new link would be created in this menu that would go to location 4(to location single)

my custom post type is currently created by a custom plugin so i would be interested in adding the code to there if possible. I saw another question that said i may have to use wp_nav_menu but i'm not sure where to start with that.

2 Answers 2

2

This should work:

add_filter( 'wp_get_nav_menu_items', 'cpt_locations_filter', 10, 3 );

function cpt_locations_filter( $items, $menu, $args ) {
  $child_items = array(); 
  $menu_order = count($items); 
  $parent_item_id = 0;

  foreach ( $items as $item ) {
    if ( in_array('locations-menu', $item->classes) ){ //add this class to your menu item
        $parent_item_id = $item->ID;
    }
  }

  if($parent_item_id > 0){

      foreach ( get_posts( 'post_type=cpt-post-type-here&numberposts=-1' ) as $post ) {
        $post->menu_item_parent = $parent_item_id;
        $post->post_type = 'nav_menu_item';
        $post->object = 'custom';
        $post->type = 'custom';
        $post->menu_order = ++$menu_order;
        $post->title = $post->post_title;
        $post->url = get_permalink( $post->ID );
        array_push($child_items, $post);
      }

  }

  return array_merge( $items, $child_items );
}
0

Did you tried with "Automatically add new-top level pages to this menu option" at the bottom of the menu page. It add's any post or page automatically to menu even if it is custom. I just have no idea about adding it to submenu.

1
  • that won't work because pages aren't actually created with custom posts. I wish it did!
    – rudtek
    Commented Oct 26, 2016 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.