[英]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.按照 woocommerce 文档,我在 woocommerce 的我的帐户页面中添加了一个端点。
I want to make this endpoint visible only to a specific user role, lets say shop_manager.我想让这个端点只对特定的用户角色可见,比如 shop_manager。
Is there a way to redirect to a 404 page users who try to access directly that endpoint?有没有办法重定向到尝试直接访问该端点的 404 页面用户?
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:假设您已经为我的帐户部分创建了一个自定义端点( 请参阅此相关答案),您可以使用
template_redirect
挂钩以这种简单的方式将所有不允许的用户角色重定向到特定页面:
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.您需要指定自定义端点、允许的用户角色和 url 重定向。
Code goes in functions.php file of your active child theme (or active theme).代码位于活动子主题(或活动主题)的 functions.php 文件中。 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 -只需在活动主题的functions.php 中添加以下代码片段,这仅适用于
administrator
用户角色,您可以根据自己的情况进行更改 -
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.在此之后,只需从后端设置 > 固定链接中
flush_rewrite_rules
。 Thats it.就是这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.