Get the post type - Wordpress menu - fatal error

Viewed 39

I have a problem with the following code:

add_action('nav_menu_css_class', 'add_current_nav_class', 10, 2 );

function add_current_nav_class($classes, $item) {
    global $post;
        
    $current_post_type = get_post_type_object(get_post_type($post->ID));
    $current_post_type_slug = $current_post_type->rewrite['slug'];
            
    $menu_slug = strtolower(trim($item->url));
    if (strpos($menu_slug,$current_post_type_slug) !== false) {
        $classes[] = 'current-menu-item';
    }
    return $classes;
}

I get the following error:

Fatal error: Uncaught Error: Undefined constant "slug" in /.../functions.php:495

Can someone please let me know what is causing this error? And how to solve it :)

EDIT: Line 495 is the following: $current_post_type_slug = $current_post_type->rewrite['slug'];

EDIT 2: If I downgrade to php 7.4, the error instead looks like this: Warning: Use of undefined constant slug - assumed 'slug' (this will throw an Error in a future version of PHP) in /customers/1/0/9/mordenfelds.se/httpd.www/wp-content/themes/mordenfelds_2017/functions.php on line 495

1 Answers

The rewrite part of the object is only accessible to custom post types, so every time its run on a page with the standard post types (post, page) its throwing the error. So modify the code to only run on a custom post type:

if ( 'YOUR_POST_TYPE' == get_post_type() ||  'YOUR_OTHER_POST_TYPE' == get_post_type())

So in your instance:

add_action('nav_menu_css_class', 'add_current_nav_class', 10, 2 );

function add_current_nav_class($classes, $item) {
    global $post;
    if( 'YOUR_POST_TYPE' == get_post_type($post->ID)){ 
        $current_post_type = get_post_type_object(get_post_type($post->ID));
        $current_post_type_slug = $current_post_type->rewrite['slug'];

        $menu_slug = strtolower(trim($item->url));
        if (strpos($menu_slug,$current_post_type_slug) !== false) {
            $classes[] = 'current-menu-item';
        }
        return $classes;
    }
}
Related