How to add custom post type archive page links to nav menu?

This is one method that I think should work (though it’s not tested).

//Hook on to the filter for the (custom) main menu
// 'wp_list_pages' filter is a fallback, when a custom menu isn't being used 
add_filter( 'wp_list_pages', 'new_nav_menu_items' );
add_filter( 'wp_nav_menu_items', 'new_nav_menu_items' );
//Can also hook into a specific menu...
//add_filter( 'wp_nav_menu_{$menu->slug}_items', 'new_nav_menu_items' );

function new_nav_menu_items($items) {
    global $wp_query;
    $class="";

    //Checks if we are viewing CPT 'myposttype', if so give it the 'active' class.
    if(isset($wp_query->query_vars['post_type'])&& $wp_query->query_vars['post_type']=='myposttype') 
        $class="current_page_item";

    //This generates the url of the CPT archive page
    $url = add_query_arg('post_type','myposttype',site_url());

    $myitem = '<li class="'.$class.'"><a href="'.$url.'">My Custom Post Type</a></li>';

    $items = $items . $myitem;
    return $items;
}

This doesn’t seem to me, to be the cleanest of solution, but I don’t know of any other way. If there is, I’d like to see it!

Finally, the link url the custom item links to is not ‘pretty’ – but you could make it so if you new the slug of the CPT (assuming custom permalinks are being used….)

Leave a Comment