WooCommerce添加到购物车重定向到上一个URL

时间:2020-07-29 16:57:52

标签: php wordpress session redirect woocommerce

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

使用following code,客户返回到特定页面(在本例中为商店页面):

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返回特定页面。在这种情况下就是商店页面

我希望将用户重定向到上一页以查看产品,任何可以帮助我的想法。

谢谢!

1 个答案:

答案 0 :(得分:0)

以下内容将保存到WC Session的简短Url历史记录,以便在添加到购物车后将客户重定向到先前的URL:

// Set prvious URL history in WC Session
add_action( 'init', 'wc_request_history' );
function wc_request_history() {
    if ( is_admin() || defined('DOING_AJAX') )
        return; // Exit

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Early enable customer session
    if ( ! WC()->session->has_session() ) {
        WC()->session->set_customer_session_cookie( true );
    }

    // 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文件中。经过测试,可以正常工作。

相关问题