0
votes

I have a woocommerce site with product reviews enabled (product reviews use the wordpress comment system). When a visitor is not logged in, this is currently shown:

You must be logged in to post a comment.

The logged in is linked to a default mysite.com/wp-login.php?redirect_to=myproduct-url. When visitors follow the link, they are taken to the default wordpress login page.

However, woocommerce has its own account login/register page, and I would like to redirect visitors to that woocommerce page instead. I'd also like to keep the automatic ?redirect_to= query so that users can be redirected back to that originating product page after they are logged in.

I'm aware that I should add a function to my theme's function.php that modifies that default link behaviour, but which filter/action do I use?

[edit] I found this

add_filter( 'login_url', 'my_login_page', 10, 2 );
function my_login_page( $login_url, $redirect ) {
    return home_url( '/my-login-page/?redirect_to=' . $redirect );
}

http://codex.wordpress.org/Plugin_API/Filter_Reference/login_url

so now I can modify the login link to use my-login-page which is great, but since it's now using the woocommerce login, I've found that woocommerce login redirects to the My Account page, and doesn't respect the ?redirect_to=myproduct-url

Any ideas on how to get the woocommerce login to follow the ?redirect_to=myproduct-url?

1

1 Answers

0
votes

You can achieve it by following code:

add_filter( 'login_url', 'my_login_page', 10, 2 );
function my_login_page( $login_url, $redirect ) {
    return home_url( '/my-login-page/?redirect_to=' . $redirect );
}

add_filter('woocommerce_login_redirect', 'rohil_login_redirect');

function rohil_login_redirect( $redirected_to ) {

    $page_url   =   $_SERVER['REQUEST_URI']; //To get string from the URL
    $current_page_url = get_permalink(); //To get URL of the current page which is MY ACCOUNT
    $encoded_url = explode('redirect_to%3D', $page_url); //To get encoded URL 
    $decoded_url    =    rawurldecode($encoded_url[1]); //To get decoded URL
    $redirection_page = explode(home_url(), $decoded_url); //Redirection page

    $redirected_to = home_url().$redirection_page[1];
    return $redirected_to;
}

Totally Untested.So please let me know the output.