Reputation: 736
i created custom checkbox on product options, but stuck in saving data. I tried all possible variants, but without success. Where i am going wrong? thanks
This is code:
add_action( 'woocommerce_product_options_sku', 'custom_checkbox_field' );
function custom_checkbox_field(){
global $post, $product_object;
if ( ! is_a( $product_object, 'WC_Product' ) ) {
$product_object = wc_get_product( $post->ID );
}
woocommerce_wp_checkbox(
array(
'id' => 'custom_checkbox_field',
'value' => empty($values) ? 'yes' : $values,
'label' => __( 'Label', 'woocommerce' ),
'description' => __( 'Description', 'woocommerce' ),
)
);
}
add_action( 'woocommerce_process_product_meta', 'save_custom_field' );
function save_custom_field( $post_id ) {
// grab the product
$product = wc_get_product( $post_id );
// save data
$product->update_meta_data( 'custom_checkbox_field', isset($_POST['custom_checkbox_field']) ? 'yes' : 'no' );
$product->save();
}
Upvotes: 3
Views: 955
Reputation: 254378
There is some missing thing in your code and your last hooked function hook can be replaced with a better one since WooCommerce version 3. Try the following instead:
add_action( 'woocommerce_product_options_sku', 'custom_checkbox_field_product_options_sku' );
function custom_checkbox_field_product_options_sku(){
global $post, $product_object;
if ( ! is_a( $product_object, 'WC_Product' ) ) {
$product_object = wc_get_product( $post->ID );
}
$values = $product_object->get_meta('custom_checkbox_field');
woocommerce_wp_checkbox( array(
'id' => 'custom_checkbox_field',
'value' => empty($values) ? 'yes' : $values, // Checked by default
'label' => __( 'Label', 'woocommerce' ),
'description' => __( 'Description', 'woocommerce' ),
) );
}
add_action( 'woocommerce_admin_process_product_object', 'save_custom_field_product_options_sku' );
function save_custom_field_product_options_sku( $product ) {
$product->update_meta_data( 'custom_checkbox_field', isset($_POST['custom_checkbox_field']) ? 'yes' : 'no' );
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Upvotes: 4