问题
When I use this function
wc_update_product_stock();
to set product stock it always saves the numeric value as float in my database.
As far as I know this function accepts three parameters
wc_update_product_stock( $product, $stock_quantity, $operation );
But when I use it like this
wc_update_product_stock( 2319 , 5 , 'set');
It stores the value of 5 as 5.000000 and this happens to any other numeric value I tried to use.
Any ideas why?
回答1:
Below is the function that updates the product stock - It uses %f
as stock quantity - So its 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' );
}
For updating directly as Integer ( as it is ) - use this function update_post_meta($product_id, '_stock', 15);
来源:https://stackoverflow.com/questions/55179909/woocommerce-wc-update-product-stock-stores-number-as-decimal-in-database