WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Add Custom Post Type to navication (2 posts)

  1. theshae
    Member
    Posted 3 years ago #

    I found a solution for treating Custom Post Types as pages. This will add them to the wp nav.

    function custom_page_menu($menu, $args) {
    
     // get supplied args
     $list_args = $args;
    
     // Overide some menu settings
     $list_args['echo'] = false;
     $list_args['title_li'] = '';
     $list_args['show_home'] = false;
     $list_args['exclude'] = 4; // excluding the homepage as I am manually adding it to the start below
    
     // get the current page object as we will need to refer to it when setting current items below
     global $wp_query;
     $current_page = $wp_query->get_queried_object();  
    
    //* Show Home item at the start of the menu
    //* $menu .= '<li ' . $class . '><a href="' . home_url( '/' ) . '" title="' . esc_attr(__('Home')) . '">' . $args['link_before'] . __('Home') . *$args['link_after'] . '</a></li>';
    
     // Loop through the custom post types and add them to the menu
     foreach(get_post_types(array(
     'public'   => true,
     '_builtin' => false,
     'hierarchical' => true
     )) as $pt) {
    
     $obj_pt = get_post_type_object($pt);
     $list_args['post_type'] = $pt;
     $menu .= '<li><a href="' . $obj_pt->rewrite['slug'] . '">' . $obj_pt->labels->name . '</a><ul>';
    
     // little bit of hacking here to force wp_list_pages to add current classes to
     // active pages in the generated navs. It's messy, but it means not having to
     // hack the WordPress core files
     $original_is_posts_page = $wp_query->is_posts_page;
     $wp_query->is_posts_page = true;
     $menu .= wp_list_pages($list_args);
     $wp_query->is_posts_page = $original_is_posts_page;
    
     $menu .= '</ul></li>';
     }
    
     // Now add the normal page collection which belongs in the nav
     $list_args['post_type'] = 'page';
     $menu .= wp_list_pages($list_args) ;
    
     // glue the menu together and send back
     if ( $menu )
     $menu = '<ul>' . $menu . '</ul>';
    
     $menu = '<div>' . $menu . "</div>\n";
    
     return $menu;
    }
    add_filter( 'wp_page_menu', 'custom_page_menu' ,10,2 );
  2. theshae
    Member
    Posted 3 years ago #

    I'm trying to get rid of the <div class="menu"></div>
    that automatically gets added to wp_nav_menu, but cant figure it out. Does anyone know how to do this?

Topic Closed

This topic has been closed to new replies.

About this Topic