我是PHP新手。我有这段代码,我想传递在函数中定义的名为$sum的全局变量post_order
to功能update_custom_meta
. 还是没有运气。我做错了什么?提前感谢您!
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\' ) ) ),
);
$orders_ids = wc_get_orders( $args );
foreach ($orders_ids as $order_id) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
global $sum;
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
if($product_id == $_GET[\'post\']) {
$product_qty = $item->get_quantity();
$sum += $product_qty;
}
}
}
}
add_action(\'init\', \'post_order\');
function update_custom_meta() {
global $post_id;
echo $sum;
$custom_value = $_POST[\'auto_restock_value\'] - $sum;
update_post_meta($post_id, \'auto_restock_value\', $custom_value);
//get_post_meta($post -> ID, \'daily_restock_amount\', true);
update_post_meta($post_id, \'_stock\', $custom_value);
}
function update_cart_stock() {
global $post_id;
//echo get_post_meta($post_id, \'total_sales\', true);
update_post_meta($post_id, \'_stock\', $custom_value);
}
add_action( \'save_post\', \'update_custom_meta\' , 10, 2 );
SO网友:csaborio
我认为你不需要使用全局变量。您定义的挂钩:
add_action( \'save_post\', \'update_custom_meta\' , 10, 2 );
您指定了两个要传递给它们的参数。如果你看看
save_post API, 您可以看到,可以将该回调定义为:
function update_cart_stock($post_ID, $post) {
global $post_id;
//echo get_post_meta($post_id, \'total_sales\', true);
update_post_meta($post_id, \'_stock\', $custom_value);
}
因此,调用save事件的post ID将作为一个参数通过。
然后,您可以将其他函数定义为:
function update_custom_meta( $post_id ) {
并从update\\u cart\\u stock中传递帖子,这有意义吗?