Updating a custom field value without manually saving in a WooCommerce admin product area

I would like to add the normal stock value of a product to the custom stock value that already has an order status (wc-on-hold and wc-processing). This works great, but only when I save the product manually. Is there a way to update the custom meta-field value without this intermediate step? Here is my Code in functions.php: // build custom Product fields function blu_real_stock_status_fields() { $domain = 'woocommerce'; echo '<div style="background:#a1ff7f;" class="options_group">'; woocommerce_wp_text_input( array( 'id' => '_realer_bestand', 'label' => __( 'Realer Bestand', $domain ), 'placeholder' => '', 'description' => __( 'Die Anzahl aller Produkte, die noch im Lager liegen.', $domain ), 'desc_tip' => true, 'custom_attributes' => array( 'readonly' => 'readonly' ), )); woocommerce_wp_text_input( array( 'id' => '_in_bearbeitung', 'label' => __( 'In Bearbeitung', $domain ), 'placeholder' => '', 'description' => __( 'Anzahl der noch nicht versandten Bestellungen.', $domain ), 'desc_tip' => true, 'custom_attributes' => array( 'readonly' => 'readonly' ), )); echo '</div>'; } add_action( 'woocommerce_product_options_stock_status','blu_real_stock_status_fields', 0, 1 ); // Get All defined statuses Orders IDs for a defined product ID (or variation ID) function get_orders_count_for_a_product( $product_id ){ $orders = wc_get_orders( array( 'numberposts' => -1, 'post_type' => 'shop_order', 'post_status' => array('wc-processing','wc-on-hold') ) ); $count_orders = 0; foreach($orders as $order){ $has_product = false; foreach($order->get_items() as $item_values) if( $item_values['product_id'] == $product_id ) $has_product = true; if( $has_product ) $count_orders++; } return $count_orders; } // Get and save Values for custom Product field function blu_real_stock_status( $product_id ) { $product = wc_get_product( $product_id ); $number_of_orders = get_orders_count_for_a_product($product_id); // Output the value $processing_val = $number_of_orders; // Isset if ( isset( $_POST['_realer_bestand'] ) ) { // ID & value $ref_stock_id = '_realer_bestand'; $ref_stock_val = $product->get_stock_quantity(); $ref_stock_val_real = $ref_stock_val + $processing_val; // Update ref stock $product->update_meta_data( $ref_stock_id, $ref_stock_val_real ); } if ( isset( $_POST['_in_bearbeitung'] ) ) { // ID & value $ref_process_id = '_in_bearbeitung'; $ref_process_val = $processing_val; // Update ref stock $product->update_meta_data( $ref_process_id, $ref_process_val ); $product->save_meta_data(); } } add_action( 'woocommerce_admin_process_product_object','blu_real_stock_status', 0, 1 );

Comment (0)

You’ll be in good company