• Home
  • Associate Custom WordPress Post Types With Menu Items



Associate Custom WordPress Post Types With Menu Items

Brandon Mack September 18, 2015 0 Comments

we ran into a problem when putting together the new website for our Saskatoon based company… aka the one you are currently on. The problem was that we had new custom post types that we created and they weren’t being associated with a parent menu item when viewing those pages.

What Was Happening

we have regular pages created called Services and Portfolio. For each of these, there is a custom post type by the same name. What we wanted to happen was when we’re viewing any of the portfolio items (custom post type of portfolio), was for the Portfolio menu item to be marked as active or current. We also wanted this same thing to happen for Services but with the custom post type called services.

What Needs To Be Done?

There’s not a whole lot involved to get this done.

First, open up the function.php file within your theme. If there isn’t one, you will have to create it. It should be located right a the base of your theme. The same place you find header.php, index.php, etc.

Next, enter the following code:

function custom_nav_class( $classes, $item ) {
    if ( get_post_type() == ‘portfolio’ && $item->title == ‘Portfolio’ ) {
        $classes[] = ‘current-menu-item’;
    elseif ( get_post_type() == ‘services’ && $item->title == ‘Services’ ) {
        $classes[] = ‘current-menu-item’;
    elseif ( get_post_type() == ‘post’ && $item->title == ‘Blog’ ) {
        $classes[] = ‘current-menu-item’;
    return $classes;
add_filter( ‘nav_menu_css_class’, ‘custom_nav_class’, 10, 2 );

For this to work for you, you will have to replace the lowercase portfolio with the custom post type you have created. Then, you will have to replace the proper case Portfolio with the menu item you want to associate this post type with. You can add as many elseif statements as you need. One for each of the custom post types.

Envisage Menu

Also note, the css in our stylesheet that styled the current menu item is called current-menu-item.

For some reason our blog posts weren’t being associated with the Blog menu item as well so we added the last elseif to cover that as well. Post type of post is now associated with the Blog menu item.

For more information on nav_menu_css_class being used, take a look at the following link:

Leave Comment

    The Goods
    Your cart is emptyReturn to Shop
      Calculate Shipping
      Apply Coupon