WooCommerce wc_update_product_stock stores number as decimal in database

Issue

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.
number 5 stored as 5.000000 in database

Any ideas why?

Solution

Below is the function that updates the product stock – It uses %f as stock quantity – So its treated as floatmore 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);

Answered By – mujuonly

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published