WooCommerce - 根据用户的角色重定向登录用户

问题描述 投票:1回答:2

这是一个基于WooCommerce Membership和Subscriptions的查询。

我必须补充一点,我也在努力决定做我正在做的事情是否是一个好的用户体验。

有很多解决方案可以在用户登录后重定向用户,但是当我们点击指向描述并允许您成为会员的页面的特定链接时,我想要重定向具有“订阅者”角色的用户。因此,虽然我不想隐藏“立即加入”等,但我只是希望将其重定向到我的帐户页面。

同样有各种角色和重定向插件,但在这个特定场景中似乎没有任何帮助。所以我使用的代码的来源是:SOURCE,我正在寻找这样的事情:

function eks_redirect_users_by_role() {

    global $post;
    $current_user   = wp_get_current_user();
    $role_name      = $current_user->roles[0];


    if ( 'subscriber' === $role_name && $post->ID == 47145)  {
        wp_redirect( '/my-account' );
    } 

} 
add_action( 'admin_init', 'eks_redirect_users_by_rol
e' );

因此,如果用户角色是订阅者并且他们尝试访问页面构思,则会重定向。

目前它确实回到了一个产品页面,上面写着“你已经拥有一个会员资格”,但这是一个到达的多个步骤。

php wordpress woocommerce woocommerce-subscriptions
2个回答
1
投票

这可能是实现您的请求更有用和正确的方法。

function redirection_based_user_role(){

    $current_user   = wp_get_current_user();
    $role_name      = $current_user->roles[0];
    $postid         = get_the_ID();

    if ( 'subscriber' === $role_name && $postid == 47145  ) {
        wp_redirect( home_url( '/my-account' ), 301 );
        exit;
    }
}
add_action( 'template_redirect', 'redirection_based_user_role' );

希望这有效。


0
投票

我能够通过以下方式达到想要的目的:

function eks_redirect_user() {

    $current_user   = wp_get_current_user();
    $role_name      = $current_user->roles[0];
    $postid = get_the_ID();

    if ( 'subscriber' === $role_name && $postid == 47145  ) { ?>
        <script>
function redirectPage() {

    window.location = "/my-account/";
}

redirectPage();
</script>

<?php
        exit;
    }

}
add_action('wp_footer', 'eks_redirect_user' );

问题是它是一个相当不整洁的解决方案,因为重定向感觉很奇怪。我不确定使用wp_redirect是否会更好。我决定只是禁用页面上的主要成员资格信息按钮,而不是将每个号召性用语重定向到帐户页面,这似乎是一个更优雅的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.