如果购物车为空,购物车页面将重定向到woocommerce中的购物页面?

Lip*_*psa 6 wordpress shopping-cart woocommerce

我正在研究wordpress woocommerce

我想在购物车页面为空时将购物车页面重定向到商店页面,否则显示购物车页面.谁能有解决方案吗?

这是我尝试过的代码,但它不起作用

function my_empty_cart() {
  global $woocommerce;

    if (isset( $_GET['empty-cart'] ) ) { 
        wp_safe_redirect( get_permalink( woocommerce_get_page_id( 'product' ) ) );
    }
}
add_action( 'init', 'my_empty_cart' );
Run Code Online (Sandbox Code Playgroud)

Pus*_*tel 11

// old woocommerce : use sizeof( $woocommerce->cart->cart_contents) to check cart content count

// In new woocommerce 2.1+ : WC()->cart->cart_contents_count to check cart content count

add_action("template_redirect", 'redirection_function');
function redirection_function(){
    global $woocommerce;
    if( is_cart() && WC()->cart->cart_contents_count == 0){
        wp_safe_redirect( get_permalink( woocommerce_get_page_id( 'shop' ) ) );
    }
}
Run Code Online (Sandbox Code Playgroud)

init钩子每次都会运行.使用template_redirect

==============Updates=============

在新的woocommerce中,他们更新了功能,现在您可以使用以下功能直接获取购物车内容数量.

WC()->cart->cart_contents_count


Loi*_*tec 8

2021 年更新

由于 WooCommerce 版本 3 在尝试访问购物车页面且购物车已为空时使用以下内容重定向到商店页面:

add_action( 'template_redirect', 'empty_cart_redirect' );
function empty_cart_redirect(){
    if( is_cart() && WC()->cart->is_empty() ) {
        wp_safe_redirect( get_permalink( wc_get_page_id( 'shop' ) ) );
        exit();
    }
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。


注释 - 已过时和已弃用的代码:

  • global $woocommerce;使用 with$woocommerce->cart简单地替换为WC()->cart
  • sizeof($woocommerce->cart->cart_contents) == 0被替换为简单的WC()->cart->is_empty()
  • woocommerce_get_page_id()被替换为wc_get_page_id()

删除购物车页面上的所有购物车商品时,要使重定向处于活动状态,需要一些额外的 jQuery 代码,请参阅:如果在 WooCommerce 3+ 中的购物车页面上清空购物车,则重定向到商店


ada*_*amj 5

因为我需要类似的东西,所以我自己测试了这个。

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' );
Run Code Online (Sandbox Code Playgroud)