WooCommerce Add to cart redirection to previous URL

自闭症网瘾萝莉.ら 提交于 2021-02-20 04:19:47

问题


At the request of users, I need the add to cart button on the individual product page to redirect users to the previous page after clicking add product to cart.

With following code, customer returns to a specific page (in this case the shop page):

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' );

with this code the users return to a specific page by means of the page id. in this case it is the store page

I would like users to be redirected to the previous page to see the product, any idea that can help me.

Thank you!


回答1:


2021 Update

The following will save to WC Session a short Url history that Will allow, on add to cart, to redirect customer to previous 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;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.



来源:https://stackoverflow.com/questions/63158723/woocommerce-add-to-cart-redirection-to-previous-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!