You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何禁止特定用户直接访问WooCommerce支付设置页面?

解决WooCommerce支付设置标签隐藏后仍可通过URL访问的问题

你当前的代码仅移除了WooCommerce设置页面的支付选项卡,但没有限制用户通过直接URL访问该页面的权限——只要知道wp-admin/admin.php?page=wc-settings&tab=checkout这个地址,未授权用户依然能进入支付设置界面。

要彻底解决这个问题,需要同时做两件事:隐藏选项卡,拦截直接访问的请求。以下是完整的解决方案:

// 移除WooCommerce设置中的支付选项卡
add_filter( 'woocommerce_settings_tabs_array', 'wd_remove_woocommerce_payment_tab', 200, 1 );
function wd_remove_woocommerce_payment_tab( $tabs_array ) {
    $wd_allowed_users = array("asd", "test", "admin"); // 替换成你允许访问的用户登录名
    $wd_user = wp_get_current_user();
    
    // 非授权用户隐藏支付选项卡
    if ( !in_array(strtolower($wd_user->user_login), $wd_allowed_users) ){
        unset( $tabs_array['checkout'] );
    }
    return $tabs_array;
}

// 阻止未授权用户通过URL直接访问支付设置
add_action( 'current_screen', 'wd_block_unauthorized_payment_settings_access' );
function wd_block_unauthorized_payment_settings_access() {
    $screen = get_current_screen();
    $wd_allowed_users = array("asd", "test", "admin"); // 和上面保持一致的允许列表
    $wd_user = wp_get_current_user();
    
    // 检查当前页面是否是支付设置页,且用户未被授权
    if ( $screen->id === 'woocommerce_page_wc-settings' && isset($_GET['tab']) && $_GET['tab'] === 'checkout' ) {
        if ( !in_array(strtolower($wd_user->user_login), $wd_allowed_users) ) {
            // 重定向到WooCommerce常规设置页(可按需修改目标地址)
            wp_redirect( admin_url('admin.php?page=wc-settings&tab=general') );
            exit;
        }
    }
}

说明

  1. 两处的$wd_allowed_users数组必须保持一致,避免出现权限逻辑矛盾
  2. 如果你想按用户角色控制(比如仅管理员可访问),可以把in_array的判断替换为角色权限检查,例如:
    if ( !current_user_can('manage_options') ) {
        // 执行隐藏/拦截操作
    }
    
  3. 重定向的目标地址可根据需求调整,比如跳转到WordPress仪表盘:wp_redirect( admin_url() );

内容的提问来源于stack exchange,提问作者Syed Tahir Rasul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 16:28:26