WooCommerce如何从模板重定向钩子中排除MyAccount的子页面(端点)? [英] Woocommerce how to exclude the child pages (endpoints) of myaccount from the template redirect hook?

查看:15
本文介绍了WooCommerce如何从模板重定向钩子中排除MyAccount的子页面(端点)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

登录-注册表单必须像弹出窗口一样显示,因此我进行了重定向,以避免未登录用户的默认MyAccount页面。

add_action( 'template_redirect', 'wish_custom_redirect' );
function wish_custom_redirect() {
  global $wp;
  if (!is_user_logged_in() &&  is_page('my-account') ) {
    wp_redirect( '/' );
    exit;
  }
}

要查看他们的帐户页面,用户必须登录或在弹出表单中注册。 但是有一个问题-/My-Account/Lost-Password/、My-Account/Reset-Password/是MyAccount的子端点。他们不必为非登录用户进行重定向。 我试着做得像那样


add_action( 'template_redirect', 'wish_custom_redirect' );
function wish_custom_redirect() {
  global $wp;
  if (!is_user_logged_in() &&  is_page('my-account') &&  !is_page('my-account/lost-password/')  ) {
    wp_redirect( '/' );
    exit;
  }
}

但它仍然可以重定向。也许这是一个糟糕的解决方案,但有更好的方法吗?或者如何使此重定向正确?

add_action('wp_logout','auto_redirect_after_logout');

function auto_redirect_after_logout(){

  wp_redirect( home_url() );
  exit();
}
仅在注销时重定向会有所帮助,但并不能避免用户看到默认页面。他们可以注销,然后返回到以前的页面/我的帐户,并查看该默认注册表单。

推荐答案

有多种方法,可以使用is_wc_endpoint_url函数,也可以使用global $wp及其名为request的属性。

既然您已经尝试了global $wp,那么我将采用相同的方法。

您的代码应该如下所示:

add_action( 'template_redirect', 'wish_custom_redirect' );

function wish_custom_redirect() {
  global $wp;

  if (
        !is_user_logged_in() 
        &&
        ('my-account' == $wp->request)
        &&
        ('lost-password' != $wp->request)
     ) 
  {
    wp_safe_redirect( site_url() );
    exit;
  }

}

已在WooCommerce5.7上测试,运行正常。


相关帖子:

用于重定向my-account页上的自定义终结点:

https://stackoverflow.com/a/70395951/15040627

这篇关于WooCommerce如何从模板重定向钩子中排除MyAccount的子页面(端点)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆