【问题标题】:WooCommerce Add to cart redirection to previous URLWooCommerce 添加到购物车重定向到以前的 URL
【发布时间】:2020-11-19 08:18:15
【问题描述】:

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

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

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

谢谢!

【问题讨论】:

  • 遵循此方法很好,但您需要以某种方式存储页面 ID,并在他们点击添加到购物车后回想一下。然后,您可以基于此重定向它们。您也可以使用 JS window.history.back(); 来完成任务。但这假设您通过 JS 添加到购物车。
  • 您应该能够在成功逻辑中使用 javascript 或 php 简单地引用引荐来源网页。.header('Location: ' . $_SERVER['HTTP_REFERER']);

标签: php wordpress session redirect woocommerce


【解决方案1】:

2021 年更新

以下内容将向 WC Session 保存一个简短的 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 文件中。经过测试并且可以工作。

【讨论】:

  • 我检查了一下,效果很好,我可以显示消息让用户知道添加的产品吗?现在它返回上一个页面没有消息,看起来像重新加载,有一个选项可以在购物车中设置返回商店链接,所以它会链接到上一个页面?
  • 我打开了你问的新问题stackoverflow.com/questions/66027579/…
  • 是问我遇到的问题的地方吗?添加代码后,我无法使用 Elementor 编辑页面和模板
  • @hanan-mstudio 我已经更新了我的答案......它应该可以解决这个问题。另请注意,此答案是针对单个产品页面添加到购物车的,因此在这种情况下会显示产品已添加到购物车的消息。
猜你喜欢
  • 2014-02-25
  • 1970-01-01
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-13
  • 2016-09-15
  • 2018-08-29
相关资源
最近更新 更多