Hide custom menu items based on session variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Nav Menu Roles + Session Roles | |
Plugin URI: http://www.kathyisawesome.com/449/nav-menu-roles/ | |
Description: Hide custom menu items based on session variables | |
Version: 1.0.0 | |
Author: Kathy Darling | |
Author URI: http://www.kathyisawesome.com | |
License: GPL-3.0 | |
Copyright 2015 Kathy Darling(email: kathy.darling@gmail.com) | |
*/ | |
/* | |
* Set session | |
*/ | |
function kia_group_session(){ | |
// start session | |
if( ! session_id() ){ | |
session_start(); | |
} | |
// if your group form is submitted store as session variable | |
if( isset( $_POST['frm1'] ) ){ | |
$_SESSION['kia-group'] = $_POST['frm1']; // maybe sanitize this | |
} | |
} | |
add_action( 'init', 'kia_group_session' ); | |
/* | |
* Add custom roles to Nav Menu Roles menu list | |
* param: $roles an array of all available roles, by default is global $wp_roles | |
* return: array | |
*/ | |
function kia_new_roles( $roles ){ | |
$roles['no-group'] = 'No Group'; | |
$roles['group-1'] = 'Group 1'; | |
$roles['group-2'] = 'Group 1'; | |
return $roles; | |
} | |
add_filter( 'nav_menu_roles', 'kia_new_roles' ); | |
/* | |
* Change visibilty of each menu item | |
* param: $visible boolean | |
* param: $item object, the complete menu object. Nav Menu Roles adds its info to $item->roles | |
* $item->roles can be "in" (all logged in), "out" (all logged out) or an array of specific roles | |
* return boolean | |
*/ | |
function kia_item_visibility( $visible, $item ){ | |
if( isset( $item->roles ) && is_array( $item->roles ) ){ | |
// get the group ID from session variable | |
$group_id = ! empty( $_SESSION['kia-group'] ) ? $_SESSION['kia-group'] : 'no-group'; | |
foreach ( $item->roles as $role ) { | |
// check all logged in, all logged out, or role | |
switch( $role ) { | |
case 'group-1' : | |
$visible = 'group-1' == $group_id ? true : false; | |
break; | |
case 'group-2' : | |
$visible = 'group-2' == $group_id ? true : false; | |
break; | |
case 'no-group' : | |
$visible = 'no-group' == $group_id ? true : false; | |
break; | |
} | |
} | |
} | |
return $visible; | |
} | |
add_filter( 'nav_menu_roles_item_visibility', 'kia_item_visibility', 10, 2 ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment