In a project that am working on, the requirement is to display different WordPress menus on different pages (views) in the Secondary Nav.
Ex.: 'Shop Menu' on a specific Shop page, 'Events Menu' when on any page generated by Modern Tribe's The Events Calendar, 'Blog Menu' in all other views etc.
Screenshots:
Front page:
Shop (a static Page):
Product 1 (sub page of Shop):
Posts page and all other views (this is like the default):
This tutorial can also be applied to conditionally show different menus in Primary Navigation Menu.
Using Genesis Simple Menus plugin is not an option because it only lets me assign menus per Post, Page, Category or Tag, but not for other views.
Using Bill Erickson's Genesis Subpages as Secondary Menu plugin is not an option because the site's navigation system isn't based on just Pages and sub Pages.
I looked at one of my earlier Posts on this topic titled How to conditionally replace Navigation menu in Genesis and figured it could be simplified and hence this tutorial.
First we are going to use a function from the codex which returns true when we are on a Page in question (by its ID) or any of its sub Pages.
Add the following in child theme's functions.php:
// Returns true when we are on a Page in question or any of its sub Pages | |
// https://codex.wordpress.org/Function_Reference/is_page#Testing_for_sub-Pages | |
function is_tree( $pid ) { // $pid = The ID of the page we're looking for pages underneath | |
global $post; // load details about this page | |
if ( is_page( $pid ) ) | |
return true; // we're at the page or at a sub page | |
$anc = get_post_ancestors( $post->ID ); | |
foreach ( $anc as $ancestor ) { | |
if( is_page() && $ancestor == $pid ) { | |
return true; | |
} | |
} | |
return false; // we aren't at the page, and the page is not an ancestor | |
} |
Now is_tree( '7' ), for example, returns true if the current page is 'Shop' (this has the ID of 7) or any of its sub Pages: 'Product 1' and 'Product 2'.
Next go ahead and create several menus for the different views. Ex.:
At Appearance > Menus > Manage Locations, assign your main or default menu to Secondary Navigation Menu location.
Finally we use wp_nav_menu_args filter to assign menus conditionally in Secondary Navigation Menu location like so:
To view the full content, please sign up for the membership.
Already a member? Log in below or here.