我正在为基于Woocommerce的面包店编写自定义插件。问题是,它有基于两天前订单的库存。产品A的产量为500件。库存减少了2天前订购的物品数量(全球总额)。我写了这个函数,它可以工作(我猜),但我仍然必须每天午夜(24:00/12 a.m.)调用这个函数
最好的解决方案是cron,我听说WP有自己的类似crown的功能,只有在有流量的情况下才能工作。
您认为在真正的cron之上使用WP-cron是个好主意吗?每天大约有100人访问page。
请您帮我编辑下面的代码,以存档这些点,好吗?
1) 每天24:002启动功能)使用custom\\u post\\u meta中的值更新库存auto_restock_value
减去前2天的订单数量(global variable $sum
). 这应该有效(?)3) 保存值并每天重复。
提前感谢您!
$post_id = $_GET[\'post\'];
function update_restock_value() {
global $post_id;
$val = get_post_meta( $post_id, \'auto_restock_value\', true );
echo \'<div class="option_group">\';
woocommerce_wp_text_input( array(
\'id\' => \'auto_restock_value_id\',
\'value\' => $val,
\'type\' => \'number\',
\'label\' => \'Auto - uzupełniany stan magazynowy\',
\'desc_tip\' => true,
\'name\' => \'auto_restock_value\',
\'description\' => \'Ta wartość, codziennie o 24:00, nadpisze stan magazynowy danego produktu\',
) );
echo \'</div>\';
}
//register_activation_hook( __FILE__, \'my_custom_cron\' );
//add_action( \'my_hourly_event\', \'do_this_hourly\' );
//function my_custom_cron() {
//wp_schedule_event( time(), \'hourly\', \'update_cart_stock\' );
//}
function post_order() {
$args = array(
\'type\' => \'shop_order\',
\'status\' => \'processing\',//zmienić//zmienić na completed
\'return\' => \'ids\',
\'date_created\' => ( date("F j, Y", strtotime( \'-2 days\' ) ) ),//list orders from 2 days before
);
global $sum;
$orders_ids = wc_get_orders( $args );
foreach ($orders_ids as $order_id) {//get order Id, and show product qty of this product
$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
if($product_id == $_GET[\'post\']) {//If product if is the same as current product, then update global $sum
$product_qty = $item->get_quantity();
$sum += $product_qty;
}
}
}
}
add_action(\'init\', \'post_order\');
function update_cart_meta() {
global $post_id;
global $sum;
echo \'<p id="sum">\' . $sum . \'</p>\';//checking if it works
update_post_meta($post_id, \'_stock\', $sum);//update stock with orders qty from 2 das before
}
add_action(\'init\', \'update_cart_meta\');
function update_custom_meta() {
global $post_id;
$custom_value = $_POST[\'auto_restock_value\'];
update_post_meta($post_id, \'auto_restock_value\', $custom_value);//update custom post meta field
}
add_action(\'save_post\', \'update_custom_meta\');
编辑:
问题2-为什么此操作返回零?
function update_cart_meta() {
global $post_id;
global $sum;
echo \'<p id="sum">\' . $sum . \'</p>\';//checking if it works (it works)
$custom_value = $_POST[\'auto_restock_value\']; //(it works)
$custom_output = $custom_value - $sum; // doesn\'t work, return 0
update_post_meta($post_id, \'_stock\', $custom_value);//update stock with orders qty from 2 days before
}
add_action(\'init\', \'update_cart_meta\');