我正在尝试创建一个 cron 作业,它将比较设置为产品元数据的日期与当前日期,然后在设置为产品元数据的日期已过时更新产品库存。
这是我到目前为止所拥有的,但它不起作用:
// Custom CRON Function
function update_pre_order_stock_status($post_id){
$current_date = date( 'YYYY-mm-dd' );
$expiryDate = $product->get_meta('woo_expiry_date');
$woo_expiry_action = $product->get_meta('woo_expiry_action');
$product_category = array( 'comic-book-pre-orders', 'dc-comics-pre-orders', 'image-comics-pre-orders', 'manga-pre-orders', 'marvel-comics-pre-orders', 'other-publisher-pre-orders');
if(( is_product_category( $product_category )) && ( $expiryDate <= $current_date ) && ( $woo_expiry_action == 'out' )) {
// 1. Updating the stock quantity
update_post_meta( $post_id, '_stock', 0);
// 2. Updating the stock quantity
update_post_meta( $post_id, '_stock_status', wc_clean( 'outofstock' ) );
// 3. Updating post term relationship
wp_set_post_terms( $post_id, 'outofstock', 'product_visibility', true );
}
}
if ( ! wp_next_scheduled( 'my_pre_order_stock_update' ) ) {
wp_schedule_event( time(), 'hourly', 'my_pre_order_stock_update' );
}
add_action( 'my_pre_order_stock_update', 'update_pre_order_stock_status' );
Cron 事件“my_pre_order_stock_update”显示在 cron 列表中,但运行它没有执行任何操作。
任何建议将非常感激!
您的代码中有很多错误:
$post_id
未定义,因为您没有将任何帖子 ID 参数传递给wp_next_scheduled
和wp_schedule_event
函数。$product
也未定义(并且实际上无法定义)。我假设您正在尝试根据以下情况更新某些特定产品:
woo_expiry_date
woo_expiry_action
因此,您需要通过
WP_Query
最简单的方法获取这些产品 ID。现在,由于 WooCommerce 从版本 3 开始迁移到自定义表,并且缓存了一些产品数据,因此您不应该再使用 WordPress post 元函数。
请尝试以下方法(未经测试):
代码位于子主题的functions.php 文件中(或插件中)。它可以工作。
注意:参数中要微调要处理的产品数量
'numberposts'
,如果要处理的产品太多,可能会导致预定的活动崩溃甚至网站崩溃。有关的: