首页 > 解决方案 > 仅为特定用户角色在 Woocommerce 中自定义我的帐户端点

问题描述

按照 woocommerce 文档,我在 woocommerce 中的我的帐户页面中添加了一个端点。

我想让这个端点只对特定的用户角色可见,比如说 shop_manager。

有没有办法重定向到尝试直接访问该端点的 404 页面用户?

提前致谢。

标签: phpwordpresswoocommerceendpointaccount

解决方案


假设您已经为我的帐户部分创建了一个自定义端点(请参阅此相关答案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;
    }
}

您需要指定自定义端点、允许的用户角色和 url 重定向。

代码在您的活动子主题(或活动主题)的functions.php 文件中。它可以工作。


有关的:


推荐阅读