如果 WooCommerce Checkout 没有产品(空购物车),则重新定向到商店页面

问题描述 投票:0回答:1

使用下面的代码,客户可以在结帐时从购物车中删除商品,但如果删除所有商品 - 客户应该被重定向到商店页面。

我已经尝试了下面的代码,但它无法正常工作,客户仍然留在“

The checkout is not available when your cart is empty
”上,后面是一个按钮,可以将客户带到商店。

这个想法不仅仅是重定向,而且还使用

wc_add_notice
显示消息。

代码的第一部分是这样的:

add_filter('woocommerce_cart_item_name', 'product_thumbnail_and_remove_on_checkout', 20, 3 );
function product_thumbnail_and_remove_on_checkout( $product_name, $cart_item, $cart_item_key ) {
if ( is_checkout() && ! is_wc_endpoint_url() ) {
$cart = WC()->cart->get_cart();
foreach ($cart as $cart_key => $cart_value){
if ($cart_key == $cart_item_key){
$product_id = $cart_item['product_id'];
$_product = $cart_item['data'] ;
$remove_product = sprintf(
'<a class="remove" style="float:left;margin-right:5px;" href="%s" title="%s" data-product_id="%s" data-product_sku="%s" data-cart_item_key="%s">&times;</a>',
esc_url(wc_get_cart_remove_url( $cart_key)), __( 'Remove From Order', 'woocommerce' ),
esc_attr($product_id),
esc_attr($_product->get_sku()),
esc_attr($cart_item_key));
}}
$product = $cart_item['data'];
$thumbnail = $product->get_image(array(50, 50));
$image_html = '<div class="product-item-thumbnail">' . $thumbnail . '</div>';
$product_name_link = '<a class="pnoc" href="' . $product->get_permalink() . '">' . $product_name . '</a>';
$product_name = $remove_product . $image_html . $product_name_link;
}
return $product_name;
}

我正在尝试使工作的代码:

add_action( 'wp_enqueue_scripts', 'cart_js_on_checkout', 10 );
function cart_js_on_checkout() {

    if ( is_checkout() ) {
    wp_enqueue_script( 'wc-cart' );
    }
}

add_action( 'template_redirect', 'redirect_empty_checkout_to_shop' );
function redirect_empty_checkout_to_shop() {

    if ( is_checkout() && WC()->cart->is_empty() && ! is_wc_endpoint_url( 'order-pay' ) && ! is_wc_endpoint_url( 'order-received' ) ) {

    wp_safe_redirect( wc_get_page_permalink( 'shop') );
    
    wc_clear_notices();
    wc_add_notice( __( 'The checkout is not available when your cart is empty. Happy shopping!', 'woocommerce' ), 'info' );
    
    }
}
php redirect woocommerce
1个回答
0
投票

我相信你会发现你遗漏了

sprintf

中的论点之一
$remove_product = sprintf(
    '<a class="remove" style="float:left;margin-right:5px;" href="%s" title="%s" data-product_id="%s" data-product_sku="%s" data-cart_item_key="%s">&times;</a>',
    esc_url(wc_get_cart_remove_url( $cart_key)), __( 'Remove From Order', 'woocommerce' ),
    //-- missing the title ~ title="%s"
    esc_attr($product_id),
    esc_attr($_product->get_sku()),
    esc_attr($cart_item_key));
}}

在这种情况下:

 cart_item_key

这不是应该的样子...

© www.soinside.com 2019 - 2024. All rights reserved.