简体   繁体   中英

Custom my account endpoint in Woocommerce just for a specific user role

Following the woocommerce documentation, I added an endpoit to my-account page in woocommerce.

I want to make this endpoint visible only to a specific user role, lets say shop_manager.

Is there a way to redirect to a 404 page users who try to access directly that endpoint?

Thanks in advance.

Assuming that you have already created a custom endpoint to my account section ( see this related answer ), you can redirect all non allowed user roles to a specific page using template_redirect hook in this simple way:

add_action( 'template_redirect', 'custom_endpoint_redirection' );
function custom_endpoint_redirection() {
    $allowed_user_role = 'administrator';
    $custom_endpoint   = 'my-custom-endpoint';

    if ( is_wc_endpoint_url($custom_endpoint) && ! current_user_can($allowed_user_role) ) {
        $redirection_url = home_url( '/404/' );

        wp_redirect( $redirection_url );
        exit;
    }
}

You need to specify your custom end point, your allowed user role and the url redirection.

Code goes in functions.php file of your active child theme (or active theme). It could works.


Related:

Just add the follows code snippet in your active theme's functions.php and this is only for administrator user role, you can change it as per you -

function add_custom_my_account_endpoint() {
    add_rewrite_endpoint( 'shop_manager', EP_PAGES );
}
add_action( 'init', 'add_custom_my_account_endpoint' );

function add_custom_wc_menu_items( $items ) {
    $user = wp_get_current_user();
    if( $user && in_array( 'administrator', $user->roles ) ){
        $items[ 'shop_manager' ] = __( 'Shop Manager', 'text-domain' );
    }
    return $items;
}
add_filter( 'woocommerce_account_menu_items', 'add_custom_wc_menu_items' );

function add_shop_manager_endpoint_content(){
    $user = wp_get_current_user();
    if( $user && !in_array( 'administrator', $user->roles ) ) return;
    echo "Your content goes here";
}
add_action( 'woocommerce_account_shop_manager_endpoint', 'add_shop_manager_endpoint_content' );

After this just flush_rewrite_rules from Backend Settings > Permalinks. Thats it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM