Skip to content

Instantly share code, notes, and snippets.

@hmouhtar
Created May 19, 2024 19:53
Show Gist options
  • Save hmouhtar/5754087d1890242494028f71959b3598 to your computer and use it in GitHub Desktop.
Save hmouhtar/5754087d1890242494028f71959b3598 to your computer and use it in GitHub Desktop.
Elementor - Replace nav menu programatically based on MemberPress membership
<?php
add_action( 'elementor/frontend/widget/before_render', function( $widget ) {
// Ensure the widget is the Nav Menu widget
if ( 'nav-menu' === $widget->get_name() ) {
// Get the widget settings
$widgetSettings = $widget->get_settings_for_display();
$widgetId = $widgetSettings['_element_id'];
// Check if the widget ID is headerNavMenu
if ( 'headerNavMenu' === $widgetId ) {
// Define the array of membership IDs
$membershipArray = [25];
$membershipList = implode( ',', $membershipArray );
// Check if the user has any of the specified memberships
if ( is_user_logged_in() && current_user_can( 'mepr-active', 'memberships:' . $membershipList ) ) {
// Define your custom menu slug here
$customMenuSlug = 'member-menu'; // Replace with your menu slug
// Get the available menus
$availableMenus = wp_get_nav_menus();
// Find the menu ID by slug
foreach ( $availableMenus as $menu ) {
if ( $menu->slug === $customMenuSlug ) {
$menuId = $menu->term_id;
break;
}
}
// If the custom menu exists, override the menu setting
if ( isset( $menuId ) ) {
$widget->set_settings( 'menu', $customMenuSlug );
}
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment