Skip to content

Instantly share code, notes, and snippets.

@EvanHerman
Created November 13, 2015 16:30
Show Gist options
  • Save EvanHerman/492c09fbb584e0c428ae to your computer and use it in GitHub Desktop.
Save EvanHerman/492c09fbb584e0c428ae to your computer and use it in GitHub Desktop.
WooCommerce - After login, redirect the user back to the last viewed product
<?php
/*
* Add a hidden field to our WooCommerce login form - passing in the refering page URL
* Note: the input (hidden) field doesn't actually get created unless the user was directed
* to this page from a single product page
*/
function redirect_user_back_to_product() {
// check for a referer
$referer = wp_get_referer();
// if there was a referer..
if( $referer ) {
$post_id = url_to_postid( $referer );
$post_data = get_post( $post_id );
if( $post_data ) {
// if the refering page was a single product, let's append a hidden field to reidrect the user to
if( isset( $post_data->post_type ) && $post_data->post_type == 'product' ) {
?>
<input type="hidden" name="redirect-user" value="<?php echo $referer; ?>">
<?php
}
}
}
}
add_action( 'woocommerce_login_form', 'redirect_user_back_to_product' );
/*
* Redirect the user back to the passed in referer page
* - Which should be the URL to the last viewed product before logging
*/
function custom_woocommerce_login_redirect_back_to_product_page( $redirect, $user ) {
if( isset( $_POST['redirect-user'] ) ) {
$redirect = esc_url( $_POST['redirect-user'] );
}
return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'custom_woocommerce_login_redirect_back_to_product_page' );
@gitatmax
Copy link

No luck for me

@multiplehats
Copy link

@maxjwhite did you ever get this to work?

@jobs-git
Copy link

jobs-git commented May 6, 2018

This is actually working, replace the last function with this

function wc_custom_user_redirect( $redirect, $user ) { $redirect = esc_url( $_POST['redirect-user'] ); return $redirect; } add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );

@multiplehats
Copy link

Sweet @jobs-git, thanks!

@AshishOdich
Copy link

AshishOdich commented Jul 26, 2018

Not worked for me

@boping
Copy link

boping commented Jan 21, 2019

Not worked for me

@fejerke00
Copy link

Replace line 9
$referer = $_SERVER['HTTP_REFERER'] ;

@nishani7234
Copy link

This is actually working, replace the last function with this

function wc_custom_user_redirect( $redirect, $user ) { $redirect = esc_url( $_POST['redirect-user'] ); return $redirect; } add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );

Thanks.

I want to redirect the user back to the last viewed product after a successful registration also. Please help me to achieve this.
Thanks in advance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment