1

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Nicola
  • 41
  • 5

2 Answers2

1

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:

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
0

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.

itzmekhokan
  • 2,597
  • 2
  • 9
  • 9
  • If an unprivileged user tries to access the endpoint directly, he does not see any error messages, what I asked is whether it is possible to redirect on page 404. – Nicola Aug 19 '19 at 12:19
  • Then just add a `if-else` logic and for unpriviledged user redirect them to 404 pages like - `if( $user && !in_array( 'administrator', $user->roles ) ) { global $wp_query; $wp_query->set_404(); status_header( 404 ); get_template_part( 404 ); exit(); } else{ echo "Your content goes here"; }` – itzmekhokan Aug 19 '19 at 12:27