WooCommerce |一个品类的产品一周只有一天可用



我是PHP和WooCommerce的绝对初学者。我们的商店向企业销售产品,但每个类别每周只在一天销售。我有"周一" "周二"之类的分类。问题是:如果有人把周一的产品放进购物车,他周二就能买到。
我想做的是在给定的日期将可用性更改为"可用",并在第二天将其更改为"不可用"。

我也不知道如何得到一个类别的所有产品。这是我尝试过的周一分类。请不要杀我…

任何帮助都非常感谢!& lt; 3

function weekday_products() {
$product_args = array(
'post_status' => 'publish',
'limit' => -1,
'category' => 'Monday',
//more options according to wc_get_products() docs
);
$products_monday = wc_get_products($product_args);
if(date('D', $timestamp) === 'Mon') {
foreach ($products_monday as $product) {
if ( !$product->is_in_stock() ) {
wc_update_product_stock_status( $product, 'instock' );
}
}
}
else {
foreach ($products_monday as $product) {
if ( $product->is_in_stock() ) {
wc_update_product_stock_status( $product, 'outofstock' );
}
}
}
}
add_action( 'only_on_weekday_products', 'weekday_products' );

目前我不能尝试代码,因为商店正在生产中。但我很确定,它无论如何都不会起作用…

编辑:另一个解决方案是在午夜清空购物车,比如:


add_action( 'woocommerce_add_cart_item_data', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
$now = strtotime("now");
$midnight = strtotime("00:00:00");
if ( $now = $midnight ) {
// Empty cart
WC()->cart->empty_cart(true);
WC()->session->set('cart', array());
}
} 

这个代码可以工作吗?

我是这样做的。将以下函数放入活动主题函数中。php

如果你想要搜索引擎优化的目的或其他东西保持显示所有的产品,那么跳过hide_products_per_day函数。只检查购物车中添加的内容。

//Show products only from specific category
function hide_products_per_day( $q ) {
$day = date('l');
$tax_query = $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field'    => 'slug', // Query by term slug
'terms'    => array( $day ), // In our case its current day
'operator' => 'IN',
);
$q->set( 'tax_query', $tax_query );
}
add_action( 'woocommerce_product_query', 'hide_products_per_day' );
function check_products_in_cart() {
if ( WC()->cart->is_empty() ) return; // Skip if cart is empty
$day = date('l');
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( !has_term( $day, 'product_cat', $cart_item['product_id'] ) ) {
WC()->cart->remove_cart_item( $cart_item_key );
wc_print_notice( $cart_item['data']->get_name().' cant be purchased today!', 'error' ); // Change type of notice if you want either error, success or notice (or custome).
}
}
}
add_action( 'woocommerce_before_checkout', 'check_products_in_cart' ); // In case we go straight to checkout
add_action( 'woocommerce_before_cart', 'check_products_in_cart' ); // We want to check what is in cart

最新更新