如果在 WooCommerce 的购物车页面上清空购物车,则重定向到商店 3+

编程入门 行业动态 更新时间:2024-10-11 13:25:02
本文介绍了如果在 WooCommerce 的购物车页面上清空购物车,则重定向到商店 3+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在 WooCommerce 中,我想在购物车为空时从购物车重定向到商店页面,并且我正在使用此代码:

In WooCommerce I want to redirect from cart to shop page when cart is empty and I am using this code:

function cart_empty_redirect_to_shop(){
    global $woocommerce;

    if ( is_page('cart') and !sizeof($woocommerce->cart->cart_contents) ) {
        wp_redirect( get_permalink( wc_get_page_id( 'shop' ) ) ); exit;
    }
}
add_action( 'wp_head', 'cart_empty_redirect_to_shop' );

此代码仅在购物车为空并且我尝试进入购物车页面时才有效.但是如果我已经在购物车页面上并且我删除了所有购物车项目,我必须重新加载页面才能重定向.所以我想我必须在代码中添加一些东西来重新加载页面.有什么想法吗?

This code works only if cart is empty and I try to go on cart page. But if I am already on cart page and I remove all cart items, I have to reload the page to get redirected. So I guess I have to add something in the code to reload the page. Any thoughts?

如果有人可以帮助我,我将不胜感激.

I would appreciate if anyone could help me with this.

推荐答案

自 WooCommerce 版本 3 以来,您的代码有点过时.现在在购物车页面上,PHP 重定向已无用,因为 清空购物车Ajax 客户现场活动.因此,在这种情况下,需要 Javascript (jQuery).

Your code is a bit obsolete since WooCommerce version 3. Now on cart page, PHP redirect is useless, because Emptying cart is an Ajax customer live event. So in this case Javascript (jQuery) is required.

改用以下内容,处理所有情况:

Use the following instead, that handle all cases:

add_action( 'template_redirect', 'empty_cart_redirection' );
function empty_cart_redirection(){
    if( is_cart() ) :
    
    // Here set the Url redirection
    $url_redirection = get_permalink( wc_get_page_id( 'shop' ) );
    
    // When trying to access cart page if cart is already empty  
    if( WC()->cart->is_empty() ){
        wp_safe_redirect( $url_redirection );
        exit();
    }
    
    // When emptying cart on cart page
    wc_enqueue_js( "jQuery(function($){
        $(document.body).on( 'wc_cart_emptied', function(){
            if ( $( '.woocommerce-cart-form' ).length === 0 ) {
                $(window.location).attr('href', '" . $url_redirection . "');
                return;
            }
        });
    });" );
    endif;
}

代码位于活动子主题(或活动主题)的functions.php 文件中.自第 3 版以来,已在所有 WooCommerce 版本中进行测试和工作.

Code goes in functions.php file of the active child theme (or active theme). Tested and works in all WooCommerce versions since version 3.

这篇关于如果在 WooCommerce 的购物车页面上清空购物车,则重定向到商店 3+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 13:17:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1173703.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:购物车   清空   重定向   商店   页面

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!