WooCommerce添加到购物车重定向到以前的URL



应用户的要求,我需要在单个产品页面上的"添加到购物车"按钮,以便在单击"将产品添加到购物中心"后将用户重定向到上一页。

使用以下代码,客户返回特定页面(在本例中为商店页面(:

function my_custom_add_to_cart_redirect( $url ) {
$url = get_permalink( 311 ); // URL to redirect to (1 is the page ID here)
return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );

使用此代码,用户通过页面id返回到特定页面。在这种情况下,它是商店页面

我希望用户被重定向到上一个页面来查看产品,任何想法都可以帮助我。

谢谢!

2021更新

以下内容将向WC会话保存一个简短的Url历史记录,该历史记录将允许在添加到购物车时将客户重定向到以前的Url:

// Early enable customer WC_Session
add_action( 'init', 'wc_session_enabler' );
function wc_session_enabler() {
if ( is_user_logged_in() || is_admin() )
return;
if ( isset(WC()->session) && ! WC()->session->has_session() ) {
WC()->session->set_customer_session_cookie( true );
}
}
// Set previous URL history in WC Session
add_action( 'template_redirect', 'wc_request_history' );
function wc_request_history() {
// Get from WC Session the request history
$history = (array) WC()->session->get('request_history');
// Keep only 2 request Urls in the array
if( count($history) > 1){
$removed = array_shift($history);
}
$current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if( ! in_array($current_url, $history) ) {
// Set current url request in the array
$history[] = $current_url;
}
// Save to WC Session the updated request history
WC()->session->set('request_history', $history);
}
// The add to cart redirect to previous URL
add_filter( 'woocommerce_add_to_cart_redirect', 'add_to_cart_redirect_to_previous_url' );
function add_to_cart_redirect_to_previous_url( $redirect_url ) {
// Get from WC Session the request history
$history = (array) WC()->session->get('request_history');
if ( count($history) == 2 ) {
$redirect_url = reset($history);
} else {
// Other custom redirection (optional)
}
return $redirect_url;
}

代码位于活动子主题(或活动主题(的functions.php文件中。测试并工作。

最新更新