WordPress.org

Ready to get started?Download WordPress

Forums

Types - Custom Fields and Custom Post Types Management
[resolved] Post type and its children show 'Blog' as the current_page_parent? (3 posts)

  1. drummerboy
    Member
    Posted 1 year ago #

    Hey guys,

    I'm having a very frustrating issue and I hope you can help. I've made a custom post type called Case Studies with the slug of casestudies and I have a custom menu item that populates the page with the Case Studies. So far so good. The problem is when you navigate to this page on the nav menu it sets the Blog page as the current_page_parent, even though it knows Case Studies in the current_menu_item. It also does this for child case study pages. I can't figure out what is going wrong here and why it is doing this? Its driving me mad! Any help would be much appreciated!

    many thanks in advance :)

    http://wordpress.org/extend/plugins/types/

  2. Matt Rittman
    Member
    Posted 1 year ago #

    The only way I could fix this issue was by adding this bit of code to the theme functions.php file:

    // Adds .current_page_parent to Custom Post Type and removes it from default "Blog"
    function add_class_to_wp_nav_menu($classes)
    {
         switch (get_post_type())
         {
         	case 'your_custom_post_type_name':
         		// we're viewing a custom post type, so remove the 'current_page_xxx and current-menu-item' from all menu items.
         		$classes = array_filter($classes, "remove_parent_classes");
    
         		// add the current page class to a specific menu item (replace ###).
         		if (in_array('menu-item-#-goes-here', $classes))
         		{
         		   $classes[] = 'current_page_parent';
                   }
         		break;
    
          // add more cases if necessary and/or a default
         }
    	return $classes;
    }
    add_filter('nav_menu_css_class', 'add_class_to_wp_nav_menu');

    Be sure to update the name of your custom post type and menu item number!

  3. swinggraphics
    Member
    Posted 6 months ago #

    After some research, I settled on this, which works perfectly:

    function is_blog() {
    	global $post;
    	$posttype = get_post_type( $post );
    	return ( ( $posttype == 'post' ) && ( is_home() || is_single() || is_archive() || is_category() || is_tag() || is_author() ) ) ? true : false;
    }
    
    function fix_blog_link_on_cpt( $classes, $item, $args ) {
    	if( !is_blog() ) {
    		$blog_page_id = intval( get_option('page_for_posts') );
    		if( $blog_page_id != 0 && $item->object_id == $blog_page_id )
    			unset($classes[array_search('current_page_parent', $classes)]);
    	}
    	return $classes;
    }
    add_filter( 'nav_menu_css_class', 'fix_blog_link_on_cpt', 10, 3 );

Topic Closed

This topic has been closed to new replies.

About this Plugin

About this Topic