I have added a custom field (radio button) with 3 options on the woocommerce product type.
I want to change the value of this custom field from “1” to “2” when that item is purchased.
Can you help me accomplish this?
Thanks in advance.
Hi,
Thank you for contacting us and I'd be happy to assist.
If your goal is to update the product's custom field value, when its order status is completed, you can use a custom function attached to WooCommerce's "woocommerce_order_status_completed" hook.
For example:
add_action('woocommerce_order_status_completed', 'custom_update_field_on_order_competed_status', 10, 1);
function custom_update_field_on_order_competed_status( $order_id ) {
// target custom field's slug
$target_field_slug = "wpcf-product-radio-field";
// get order info
$order = wc_get_order( $order_id );
// cycle through each product included in the order
foreach ( $order->get_items() as $item_id => $product_item ) {
// get the ID of the ordered product
$product_id = $product_item->get_product_id();
// get current field value
$current_field_value = get_post_meta($product_id, $target_field_slug, true);
// if value is not already equal to 2, set it to 2
if ($current_field_value != 2) {
update_post_meta( $product_id, $target_field_slug, 2 );
}
}
}
The above code snippet can be included through either Toolset's custom code feature ( ref: https://toolset.com/documentation/adding-custom-code/using-toolset-to-add-custom-code/ ) or through the active theme's "functions.php" file.
Note: The custom code examples from our forum are shared to get you started in the right direction. You're welcome to adjust them as needed and for more personalized customization assistance, you can consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/
regards,
Waqar