WooCommerce wc_update_product_stock 在数据库中以十进制形式存储数字 [英] WooCommerce wc_update_product_stock stores number as decimal in database

查看:45
本文介绍了WooCommerce wc_update_product_stock 在数据库中以十进制形式存储数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用这个功能时

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 ); 

但是当我这样使用它时

wc_update_product_stock( 2319 , 5 , 'set');

它将 5 的值存储为 5.000000,这发生在我尝试使用的任何其他数值上.

It stores the value of 5 as 5.000000 and this happens to any other numeric value I tried to use.

知道为什么吗?

推荐答案

下面是更新产品库存的函数 - 它使用 %f 作为库存数量 - 所以它的 被视为浮动 - 更多详情

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' );
    }

为了直接更新为整数(原样) - 使用这个函数 update_post_meta($product_id, '_stock', 15);

For updating directly as Integer ( as it is ) - use this function update_post_meta($product_id, '_stock', 15);

这篇关于WooCommerce wc_update_product_stock 在数据库中以十进制形式存储数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆