使用此功能时
wc_update_product_stock();
要设置产品库存,它总是将数值保存为浮点数在我的数据库中。
据我所知,此函数接受三个参数
wc_update_product_stock( $product, $stock_quantity, $operation );
但是当我这样使用它
wc_update_product_stock( 2319 , 5 , 'set');
它将5的值存储为5.000000,这与我尝试使用的任何其他数字值相同。
有什么想法吗?
答案 0 :(得分:1)
下面是更新产品库存的功能-它使用%f
作为库存数量-因此其treated as float
-more details
public function update_product_stock( $product_id_with_stock, $stock_quantity = null, $operation = 'set' ) {
global $wpdb;
add_post_meta( $product_id_with_stock, '_stock', 0, true );
// Update stock in DB directly.
switch ( $operation ) {
case 'increase':
// phpcs:ignore WordPress.VIP.DirectDatabaseQuery.DirectQuery
$wpdb->query(
$wpdb->prepare(
"UPDATE {$wpdb->postmeta} SET meta_value = meta_value + %f WHERE post_id = %d AND meta_key='_stock'",
$stock_quantity,
$product_id_with_stock
)
);
break;
case 'decrease':
// phpcs:ignore WordPress.VIP.DirectDatabaseQuery.DirectQuery
$wpdb->query(
$wpdb->prepare(
"UPDATE {$wpdb->postmeta} SET meta_value = meta_value - %f WHERE post_id = %d AND meta_key='_stock'",
$stock_quantity,
$product_id_with_stock
)
);
break;
default:
// phpcs:ignore WordPress.VIP.DirectDatabaseQuery.DirectQuery
$wpdb->query(
$wpdb->prepare(
"UPDATE {$wpdb->postmeta} SET meta_value = %f WHERE post_id = %d AND meta_key='_stock'",
$stock_quantity,
$product_id_with_stock
)
);
break;
}
wp_cache_delete( $product_id_with_stock, 'post_meta' );
}
要直接以Integer形式更新(按原样),请使用此功能update_post_meta($product_id, '_stock', 15);