How to Add Conditional Logic to Menus in WordPress

172

Do you want to show different navigation menu items for different pages in WordPress? Perhaps showing a different menu to logged in users, or hiding a menu item on particular pages? Normally it would require you to add code snippets or use CSS to hide menu items, but wouldn’t it be great if you could do that inside your WordPress admin area? In this article, we will show you how to add conditional logic to menus in WordPress.

Video Tutorial

Subscribe to WPBeginner

If you don’t like the video or need more instructions, then continue reading.
First thing you need to do is install and activate the If Menu plugin. It works out of the box. All you need to do is visit Appearance » Menus and start editing your navigation menus.

Start by selecting an item in the navigation menu and click the ‘Enable Conditional Logic’ checkbox. This will show the conditional menu, which looks like this:

Conditional menu

Next, choose whether you want to show or hide that item and then choose the condition. For example, only show the logout page link when a user is logged in.

After choosing a condition, simply press the save menu button to store your changes.

Adding Your Own Conditions

If Menu is a new plugin, and there are not many conditions that you can apply. WordPress provides many more conditional tags that you can use in your projects. For a full list check out this page.

You can add any of these conditional tags to be used with the If Menu plugin. For example, let’s assume that you want to show/hide a menu item on custom post type pages.

You would add the code snippet to your theme’s functions.php file or a site-specific plugin like this.

  add_filter( 'if_menu_conditions', 'wpb_new_menu_conditions' );    function wpb_new_menu_conditions( $conditions ) {    $conditions[] = array(      'name'    =>  'If it is Custom Post Type archive', // name of the condition      'condition' =>  function($item) {          // callback - must return TRUE or FALSE        return is_post_type_archive();      }    );      return $conditions;  }  

This is how it would appear in the conditional logic menu.

Adding your own conditions in the conditional menus

That’s all. We hope this article helped you add conditional logic to menus in WordPress. You may also want to check out our guide on how to style WordPress navigation menus.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Google+.