简体   繁体   English

基于WooCommerce产品当前库存值的自定义库存字段计算

[英]Custom stock field calculation based on current stock value of WooCommerce Product

I'm making an effort to improve my inventory management and do it straight from WooCommerce (So that it's not necessary to to use external CSV file calculations)我正在努力改善我的库存管理,并直接从 WooCommerce 开始(这样就没有必要使用外部 CSV 文件计算)

I need to know how much much of each product I need to order (Missing stock).我需要知道每种产品需要订购多少(缺货)。 To determine this I calculate using _stock native value and 2 custom fields:为了确定这一点,我使用_stock原生值和 2 个自定义字段进行计算:

_missing_stock : Amount of missing stock / how much stock I need to order _missing_stock :缺少的库存数量/我需要订购多少库存

_ref_stock : Reference stock number (set manually, desired amount of stock in the warehouse) _ref_stock :参考库存编号(手动设置,仓库中所需的库存数量)

so: Missing Stock = Reference stock - Stock value所以:缺失库存 = 参考库存 - 库存价值


The intention is to automatically calculate and update the Missing Stock value based on the Reference Stock that has been set and the Current Stock of the product.目的是根据已设置的参考库存和产品的当前库存自动计算和更新缺失库存值。 As a product stock lowers with purchases, with this I am quickly able to view how much stock of each product needs to be ordered.由于产品库存随着购买而降低,因此我可以快速查看每种产品需要订购多少库存。

Based on Product regular price calculation based on 2 custom fields in Woocommerce 3 answer code which has some similarities I have managed to create the custom fields and come so far.基于基于Woocommerce 3 答案代码中的 2 个自定义字段的产品正常价格计算,我已经设法创建了自定义字段并到目前为止。

However I am not able to figure out how to finally automatically update the _missing_stock value automatically.但是我无法弄清楚如何最终自动更新 _missing_stock 值。

This is the code I have managed to come up to, naturally (and probably) not entirely correct.这是我设法提出的代码,自然(并且可能)不完全正确。

// Adding and displaying additional Stock custom fields
add_action( 'woocommerce_product_options_stock_status', 'additional_product_stock_option_fields', 50 );
function additional_product_stock_option_fields() {
    $domain = "woocommerce";
    global $post;

    echo '</div><div class="options_group stock show_if_simple show_if_external show_if_composite">';

    woocommerce_wp_text_input( array(
        'id'            => '_ref_stock',
        'label'         => __("Reference Stock", $domain ),
        'placeholder'   => '',
        'description'   => __("Amount of desired target stock in warehouse )", $domain ),
        'desc_tip'      => true,
    ) );


    woocommerce_wp_text_input( array(
        'id'            => '_missing_stock',
        'label'         => __("Missing Stock", $domain ) . ' ('. get_woocommerce_currency_symbol() . ')',
        'placeholder'   => '',
        'description'   => __("Amount of stock that needs to be ordered", $domain ),
        'desc_tip'      => true,
    ) );

    echo '<input type="hidden" name="_custom_stock_nonce" value="' . wp_create_nonce() . '">';

}

// Utility function that save "Reference Stock" and "missing_stock" custom fields values
function saving_ref_stock_and_missing_stock( $product ) {
    // Security check
    if ( isset($_POST['_custom_stock_nonce']) && ! wp_verify_nonce($_POST['_custom_stock_nonce']) ) {
        return;
    }

    // Save "Reference Stock" and "missing_stock" custom fields values
    if( isset($_POST['_ref_stock']) && isset($_POST['_missing_stock']) ) {
        $product->update_meta_data('_ref_stock', sanitize_text_field( (float) $_POST['_ref_stock'] ) );
        $product->update_meta_data('_missing_stock', sanitize_text_field( (float) $_POST['_missing_stock'] ) );
    }
}

// Utility function: Calculate and save product "missing stock" custom field from the "Reference Stock" custom field and the "Stock" field
function calculate_and_save_new_product_stock( $product ) {

// Check if product stock management is enabled
 if ( !$product->managing_stock() ) {
    // Calculate and save the missing stock
    if( isset($_POST['_ref_stock']) && isset($_POST['_missing_stock'])
    && $_POST['_ref_stock'] > 0 && $_POST['_missing_stock'] > 0 ) {

        // Catch the stock data
        $ref_stock    = (float) $_POST['_ref_stock'];
        $missing_stock = (float) $_POST['_missing_stock'];
        $current_stock   = (float) $product->get_stock_quantity();

        // Calculating missing stock
        $missing_stock  = $ref_stock - $current_stock;

     
        }
    }
}

// Saving and calculating Stock values
add_action( 'woocommerce_admin_process_product_object', 'update_product_meta_data', 100, 1 );
function update_product_meta_data( $product ) {

    // Saving "Reference Stock" and "missing_stock" custom fields values
    saving_ref_stock_and_missing_stock( $product ); // <== To be removed if not used with the first function

    // Calculate and save Missing Stock from the "Reference Stock" and the "Stock" custom fields
    calculate_and_save_new_product_missing_stock( $product );
}

Thank you in advance for the attention and advice.提前感谢您的关注和建议。

The code you are already using and have adapted is slightly more extensive than your question, so below is a simplified version.您已经使用并已调整的代码比您的问题稍微广泛,因此以下是简化版本。

You can indeed use woocommerce_admin_process_product_object when you are going to save the adjustment in the backend to determine the value of the custom field.当您要在后端保存调整以确定自定义字段的值时,您确实可以使用woocommerce_admin_process_product_object

However, after an order when an adjustment of the stock takes place, the value of your custom field will not automatically adjust.但是,在订单发生库存调整后,您的自定义字段的值不会自动调整。

For that you can use the woocommerce_product_set_stock action hook.为此,您可以使用woocommerce_product_set_stock操作挂钩。

This code is written for 'simple' products but can easily be extended to other types of products if desired.此代码是为“简单”产品编写的,但如果需要,可以很容易地扩展到其他类型的产品。

Explanation via comment tags added via in the code通过在代码中添加的注释标签进行解释

// Adding and displaying additional custom fields
function action_woocommerce_product_options_stock_status() {
    $domain = 'woocommerce';
    
    echo '</div><div class="options_group">';
    
    woocommerce_wp_text_input( array(
        'id'                 => '_ref_stock',
        'label'              => __( 'Reference Stock', $domain ),
        'placeholder'        => '',
        'description'        => __( 'Amount of desired target stock in warehouse', $domain ),
        'desc_tip'           => true,
    ));

    woocommerce_wp_text_input( array(
        'id'                 => '_missing_stock',
        'label'              => __( 'Missing Stock', $domain ),
        'placeholder'        => '',
        'description'        => __( 'Amount of stock that needs to be ordered', $domain ),
        'desc_tip'           => true,
        'custom_attributes'  => array( 'readonly' => 'readonly' ),
    ));
}
add_action( 'woocommerce_product_options_stock_status', 'action_woocommerce_product_options_stock_status', 10, 1 );

// Save custom field
function action_woocommerce_admin_process_product_object( $product ) {
    // Isset
    if ( isset( $_POST['_ref_stock'] ) ) {
        // ID & value
        $ref_stock_id = '_ref_stock';
        $ref_stock_val = sanitize_text_field( $_POST['_ref_stock'] );
        
        // Update ref stock
        $product->update_meta_data( $ref_stock_id, $ref_stock_val );
        
        // Get stock quantity
        $current_stock = (float) $product->get_stock_quantity();

        // NOT empty
        if ( ! empty ( $current_stock ) ) {
            // ID
            $missing_stock_id = '_missing_stock';
            
            // Calculating missing stock
            $missing_stock_val = $ref_stock_val - $current_stock;
            
            // Update missing stock
            $product->update_meta_data( $missing_stock_id, $missing_stock_val );
        }
    }
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );

// When the stock changed
function action_woocommerce_product_set_stock ( $product_with_stock ) {
    global $pagenow;

    // Exit
    if ( is_admin() && $pagenow === 'post.php' )
        return;
    
    // Get meta
    $ref_stock_val = $product_with_stock->get_meta( '_ref_stock' );
    
    // NOT empty
    if ( ! empty ( $ref_stock_val ) ) {
        // Get stock quantity
        $current_stock = (float) $product_with_stock->get_stock_quantity();

        // NOT empty
        if ( ! empty ( $current_stock ) ) {
            // ID
            $missing_stock_id = '_missing_stock';
            
            // Calculating missing stock
            $missing_stock_val = $ref_stock_val - $current_stock;
            
            // Update missing stock
            $product_with_stock->update_meta_data( $missing_stock_id, $missing_stock_val );
            
            // Save
            $product_with_stock->save();
        }       
    }
}
add_action( 'woocommerce_product_set_stock', 'action_woocommerce_product_set_stock', 10, 1 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM