admin管理员组

文章数量:1122846

currently i have, as custom field on buddypress registration, the option to register as User Type A or User Type B. I want to show a menu for user type a and another menu for user type b. How can i achieve that?

currently i have, as custom field on buddypress registration, the option to register as User Type A or User Type B. I want to show a menu for user type a and another menu for user type b. How can i achieve that?

Share Improve this question asked Aug 10, 2024 at 17:05 B ProjectB Project 31 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

This can be done by registering different menu location for different users and then update location according to the User type which user selected during the registration time.

We need to add the given code to functions.php file of the theme.

In this code we are registering custom menus.

function custom_menus_registration() {
    register_nav_menus(
        array(
        'user_type_a_menu' => __('User Type Menu A'),
        'user_type_b_menu' => __('User Type Menu B')
        )
    );
}
add_action('init', 'custom_menus_registration');

In this step we are updating User type meta according to User selection.

add_action( 'bp_core_signup_user', 'save_user_type_on_registration' );
function save_user_type_on_registration($user_id) {
    if ( isset( $_POST['user_type'] ) ) {
        update_user_meta( $user_id, 'user_type', sanitize_text_field( $_POST['user_type'] ) );
    }
}

Here we are using this code to conditionally display different menus based on the user type.

function custom_menu_based_on_user_type( $args ) {
    if ( is_user_logged_in() ) {
        $user_id   = get_current_user_id();
        $user_type = get_user_meta( $user_id, 'user_type', true );

        if ( $user_type == 'User Type A' ) {
            $args['theme_location'] = 'user_type_a_menu';
        } elseif ( $user_type == 'User Type B' ) {
            $args['theme_location'] = 'user_type_b_menu';
        }
    }

    return $args;
}
add_filter( 'wp_nav_menu_args', 'custom_menu_based_on_user_type' );

本文标签: conditional menu with custom fields