How to Add Conditional Logic to Menus in WordPress

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.

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:

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.

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+.

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!

Pin It on Pinterest

Add address