Remove menu item from WordPress navigation menu

Today I needed to dynamically modify wordpress navigation menu from a custom plugin depending on some conditions. I couldn’t find the solution. So I read the codes which renders navigation menu on wordpress to remove some items from menu on-the-fly:

 

Filter: wp_nav_menu_objects

 

add_filter( 'wp_nav_menu_objects', array ( $this, 'frontend_menu' ), 100, 2 );

    public function frontend_menu( $sorted_menu_items, $args ) {

        /* Unsetting menu object depending on some conditions */
        foreach ($sorted_menu_items as $index => $post) {

            if( $post->post_name == 'member-area' ) {

                if( ! SMC_ACL::has_feature( 'backend' ) ) {

                    unset( $sorted_menu_items[$index] );

                }

            }

        }
        return $sorted_menu_items;
   }

You can attach any function to the filter. I just added a object function. The main idea is look and unset the menu object that you need to remove.

In the similar fashion, I think you can also modify a menu object, or even create a virtual menu item (which I don’t recommend, rather create in admin area, and remove if not needed dynamically).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s