Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce how to exclude the child pages (endpoints) of myaccount from the template redirect hook?

The login-register form has to be shown only like popup, so I've made redirect, to avoid default myaccount page for not logged users.

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;
  }
}

To view their account page users have to log in or register in popup form. But there is a problem - /my-account/lost-password/, my-account/reset-password/ are children-endpoints of myaccount. They have not to make redirect for non-logged users. I tried to make like that


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;
  }
}

But it still redirects. Maybe it's a bad solution at all and there's a better way? Or how to make this redirect correctly?

add_action('wp_logout','auto_redirect_after_logout');

function auto_redirect_after_logout(){

  wp_redirect( home_url() );
  exit();
}

To redirect only on logout helps, but doesn't avoid user to see the default page. They can logout, and then return on the prevous page /myaccount, and see that default register form.

like image 786
libertarian Avatar asked Nov 27 '21 16:11

libertarian


1 Answers

There are multiple ways to do this, you could use is_wc_endpoint_url function, or you could use global $wp and its property called request as well.

Since you've already tried global $wp, then I'll take the same approach.

Your code would be something like this:

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;
  }

}

It's been tested on woocommerce 5.7 and works fine.


Related Post:

For redirecting custom endpoint on my-account page:

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

like image 179
Ruvee Avatar answered Oct 23 '22 02:10

Ruvee