WooCommerce woa_remove_header_cart 如果用户未登录

WooCommerce woa_remove_header_cart if user not logged in

我只想在用户登录时显示 header 购物车(位于菜单上)。这是我目前得到的结果:

add_action('init','remove_header_cart_if_user_not_logged_in');

function remove_header_cart_if_user_not_logged_in() {
    if (is_user_logged_in()) {
        return;
    } else {
        add_action( 'init', 'woa_remove_header_cart' );

    function woa_remove_header_cart() {
        remove_action( 'storefront_header', 'storefront_header_cart', 60 );
    }
}

此代码会产生错误并阻止我的网站显示。 " [域] 页面不工作 [域] 当前无法处理此请求。 HTTP 错误 500

单独的 else 部分 (woa_remove_header_cart) 运行良好,但是当我尝试将它放在 "if user logged in" 条件中时,它会产生错误。

如果将其简化为:

add_action( 'storefront_header','remove_header_cart_if_user_not_logged_in' );

function remove_header_cart_if_user_not_logged_in() {
    if ( ! is_user_logged_in() ) {
        remove_action( 'storefront_header', 'storefront_header_cart', 60 );
    }
}

您要同时向 init 挂钩添加两个函数 time/priority?这充其量很奇怪,可能会导致您的错误。我也不确定 WP 是否知道用户是通过 init 登录的。现在没有时间检查,但你可以避免它。您不必删除 init 挂钩上的函数,只需在函数执行之前删除即可。在我的示例中,我使用了 storefront_header 挂钩,但由于默认 (10) 优先级低于 60 它应该可以工作。