在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' );
// 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' ) ) );
}
}
init
钩子将每次运行。使用template_redirect
==============Updates=============
在新的woocommerce中,他们已经更新了功能,现在您可以使用以下功能直接获取购物车内容计数。
WC()->cart->cart_contents_count
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();
}
}
代码放在活动子主题(或活动主题)的functions.php文件中。
注释-废弃和弃用的代码:
-
global $woocommerce;
与$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中被清空
我自己测试了一下,因为我需要类似的东西。
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' );
我尝试了@Pushpak的解决方案,但它不再工作了。查看购物车内容请使用以下代码:
global $woocommerce;
if ( $woocommerce->cart->cart_contents_count != 0 ) {
// cart has content
} else {
// cart is empty
}
2018 - 9月25日
今天为我工作::
function cart_empty_redirect_to_shop() {
global $woocommerce, $woocommerce_errors;
if ( is_cart() && sizeof($woocommerce->cart->cart_contents) == 0) {
wp_safe_redirect( get_permalink( wc_get_page_id( 'shop' ) ) );
exit;
}
}
add_action( 'template_redirect', 'cart_empty_redirect_to_shop' );
直接进入woocommerce文件夹并导航到CART文件夹。里面有一个cart-empty.php
则找到以下内容:
<p><a class="button1 btn btn-normal" href="<?php echo get_permalink.....
它会说getpermalink(woocommerce_.....
改成
<p><a class="button1 btn btn-normal" href="<?php echo get_permalink('THE PAGE ID YOU WANT TO REDIRECT TO');
和鲍勃你的叔叔…它将重定向到您指定id的页面。