WordPress.org

Forums

Custom Post type register current menu item (1 post)

  1. emsbypixel
    Member
    Posted 10 months ago #

    Hi,

    I have many custom post types on my website. However, I can only get the ancestor menu item highlighted when I copy and paste the following code:

    function nav_parent_class($classes, $item) {
        $cpt_name = 'products';
        $parent_slug = 'products';
    
        if ($cpt_name == get_post_type() && !is_admin()) {
            global $wpdb;
    
            // get page info (we really just want the post_name so it can be compared to the post type slug)
            $page = get_page_by_title($item->title, OBJECT, 'page');
    
            // check if slug matches post_name
            if( $page->post_name == $parent_slug ) {
                $classes[] = 'current_page_parent';
            }
    
        }
    
        return $classes;
    }
    
    add_filter('nav_menu_css_class', 'nav_parent_class', 10, 2);

    However, i need to keep copy and pasting each time i add a new custom post type. Can i make it more dynamic?

Reply

You must log in to post.

About this Topic