wordpress 非登录用户当试图看到一个产品页面将获得登录页面,登录后将被重定向到用户之前点击的产品页面

ghhkc1vu  于 5个月前  发布在  WordPress
关注(0)|答案(1)|浏览(76)

我想给给予访问吴产品单页登录用户只。
我有一个在主页和商店页面上的产品列表,我想要的是:当一个注销的用户点击产品,用户将得到一个登录表单,登录后用户将被重定向到他想要查看的产品页面。
因此,流程将类似于:主页/商店->单击产品X ->登录页面->重定向到产品X单页目前,我正在使用由此函数woocommerce_login_form()创建的常规Woo登录表单。
我正在尝试下面的代码片段:

add_filter('login_redirect', 'my_login_redirect', 10, 3);
    function my_login_redirect() {
        $location = $_SERVER['HTTP_REFERER'];
        var_dump($location);
        wp_safe_redirect($location);
        exit();
    }
}

add_action('init','my_login_redirect');
function my_login_redirect() {
        $location = $_SERVER['HTTP_REFERER'];
        var_dump($location);
        //wp_safe_redirect($location);
    }
-----------------------
AND ALSO THIS ONE
-----------------------
function redirect_after_login(){
  global $wp;
  $protocol='http';
  if (isset($_SERVER['HTTPS']))
    if (strtoupper($_SERVER['HTTPS'])=='ON')
      $protocol='https';
  if (!is_user_logged_in() && is_product() ){
    $redirect = site_url() . "/my-account.php?redirect_to= $protocol://" . 
$_SERVER["HTTP_HOST"] . urlencode($_SERVER["REQUEST_URI"]);
    wp_redirect( $redirect );
    exit;
  }
}
add_action( 'wp', 'redirect_after_login', 3 );

In both of cases, the problem is, it always find the Login page as HTTP_REFERER / REQUEST_URI

Because currently, I am using below code to redirect Non-logged-in user who is trying to see the product page to the Login page:

add_action('template_redirect', 'ethis_redirect_for_loggedin_users');
function ethis_redirect_for_loggedin_users() {
if ( !is_user_logged_in() && is_product() ) {
wp_redirect(site_url().'/default-login');
exit;
}
}

字符串

q0qdq0h2

q0qdq0h21#

您可以使用template_redirect过滤器钩子来阻止访客用户访问单个产品页面。

add_action( 'template_redirect', 'wc_redirect_non_logged_to_login_access');
function wc_redirect_non_logged_to_login_access() {
    if ( !is_user_logged_in() && is_singular( 'product' ) ) {
        global $post;
        wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id')).'?redirect='.get_the_permalink( $post->ID ) );
        exit();
    }
}

字符串
然后,你必须使用woocommerce_login_redirect过滤器钩子进行登录重定向。

add_filter( 'woocommerce_login_redirect', 'my_login_redirect', 10, 2 );
function my_login_redirect( $redirect, $user ) {
    if( isset( $_GET['redirect'] ) && $_GET['redirect'] != '' ){
        return $_GET['redirect'];
    }
    return $redirect;
}


代码将进入您的活动主题functions.php Tested and Works。

相关问题