PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 8, 2022

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

 January 08, 2022     hook-woocommerce, php, redirect, woocommerce, wordpress     No comments   

Issue

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.


Solution

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



Answered By - Ruvee
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing