Multi Checkbox Fields in Woocommerce Backend

Multi checkbox fields in Woocommerce backend

2021 Update

2021 Update - Solved issues with:

in_array() where 2nd argument was a string on start*.

$thepostid as in some cases it was empty.

That is possible creating a custom function this way:

// New Multi Checkbox field for woocommerce backend
function woocommerce_wp_multi_checkbox( $field ) {
global $thepostid, $post;

if( ! $thepostid ) {
$thepostid = $post->ID;
}

$field['value'] = get_post_meta( $thepostid, $field['id'], true );

$thepostid = empty( $thepostid ) ? $post->ID : $thepostid;
$field['class'] = isset( $field['class'] ) ? $field['class'] : 'select short';
$field['style'] = isset( $field['style'] ) ? $field['style'] : '';
$field['wrapper_class'] = isset( $field['wrapper_class'] ) ? $field['wrapper_class'] : '';
$field['value'] = isset( $field['value'] ) ? $field['value'] : array();
$field['name'] = isset( $field['name'] ) ? $field['name'] : $field['id'];
$field['desc_tip'] = isset( $field['desc_tip'] ) ? $field['desc_tip'] : false;

echo '<fieldset class="form-field ' . esc_attr( $field['id'] ) . '_field ' . esc_attr( $field['wrapper_class'] ) . '">
<legend>' . wp_kses_post( $field['label'] ) . '</legend>';

if ( ! empty( $field['description'] ) && false !== $field['desc_tip'] ) {
echo wc_help_tip( $field['description'] );
}

echo '<ul class="wc-radios">';

foreach ( $field['options'] as $key => $value ) {

echo '<li><label><input
name="' . esc_attr( $field['name'] ) . '"
value="' . esc_attr( $key ) . '"
type="checkbox"
class="' . esc_attr( $field['class'] ) . '"
style="' . esc_attr( $field['style'] ) . '"
' . ( is_array( $field['value'] ) && in_array( $key, $field['value'] ) ? 'checked="checked"' : '' ) . ' /> ' . esc_html( $value ) . '</label>
</li>';
}
echo '</ul>';

if ( ! empty( $field['description'] ) && false === $field['desc_tip'] ) {
echo '<span class="description">' . wp_kses_post( $field['description'] ) . '</span>';
}

echo '</fieldset>';
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Related: Multi Select fields in Woocommerce backend


Usage example (for a simple product):

// Add custom multi-checkbox field for product general option settings
add_action( 'woocommerce_product_options_general_product_data', 'add_custom_settings_fields', 20 );
function add_custom_settings_fields() {
global $post;

echo '<div class="options_group hide_if_variable"">'; // Hidding in variable products

woocommerce_wp_multi_checkbox( array(
'id' => '_custom_level',
'name' => '_custom_level[]',
'label' => __('Levels', 'woocommerce'),
'options' => array(
'MBO' => __( 'MBO', 'woocommerce' ),
'HBO' => __( 'HBO', 'woocommerce' ),
'WO' => __( 'WO', 'woocommerce' )
)
) );

echo '</div>';
}

// Save custom multi-checkbox fields to database when submitted in Backend (for all other product types)
add_action( 'woocommerce_process_product_meta', 'save_product_options_custom_fields', 30, 1 );
function save_product_options_custom_fields( $post_id ){
if( isset( $_POST['_custom_level'] ) ){
$post_data = $_POST['_custom_level'];
// Data sanitization
$sanitize_data = array();
if( is_array($post_data) && sizeof($post_data) > 0 ){
foreach( $post_data as $value ){
$sanitize_data[] = esc_attr( $value );
}
}
update_post_meta( $post_id, '_custom_level', $sanitize_data );
}
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Sample Image

The selected values are correctly saved and displayed. For info the value is an array.

Metabox with multi checkbox in WooCommerce admin single orders

There was another issue with the function woocommerce_wp_multi_checkbox() that I have updated again (when used in a custom metabox).

I have also revisited all your code, specially the last function that saves the multi-checkboxes selected values.

The complete code:

// WooCommerce admin custom multi checkbox field function
function woocommerce_wp_multi_checkbox( $field ) {
global $thepostid, $post;

if( ! $thepostid ) {
$thepostid = $post->ID;
}

$field['value'] = get_post_meta( $thepostid, $field['id'], true );

$thepostid = empty( $thepostid ) ? $post->ID : $thepostid;
$field['class'] = isset( $field['class'] ) ? $field['class'] : 'select short';
$field['style'] = isset( $field['style'] ) ? $field['style'] : '';
$field['wrapper_class'] = isset( $field['wrapper_class'] ) ? $field['wrapper_class'] : '';
$field['value'] = isset( $field['value'] ) ? $field['value'] : array();
$field['name'] = isset( $field['name'] ) ? $field['name'] : $field['id'];
$field['desc_tip'] = isset( $field['desc_tip'] ) ? $field['desc_tip'] : false;

echo '<fieldset class="form-field ' . esc_attr( $field['id'] ) . '_field ' . esc_attr( $field['wrapper_class'] ) . '">
<legend>' . wp_kses_post( $field['label'] ) . '</legend>';

if ( ! empty( $field['description'] ) && false !== $field['desc_tip'] ) {
echo wc_help_tip( $field['description'] );
}

echo '<ul class="wc-radios">';

foreach ( $field['options'] as $key => $value ) {

echo '<li><label><input
name="' . esc_attr( $field['name'] ) . '"
value="' . esc_attr( $key ) . '"
type="checkbox"
class="' . esc_attr( $field['class'] ) . '"
style="' . esc_attr( $field['style'] ) . '"
' . ( is_array( $field['value'] ) && in_array( $key, $field['value'] ) ? 'checked="checked"' : '' ) . ' /> ' . esc_html( $value ) . '</label>
</li>';
}
echo '</ul>';

if ( ! empty( $field['description'] ) && false === $field['desc_tip'] ) {
echo '<span class="description">' . wp_kses_post( $field['description'] ) . '</span>';
}

echo '</fieldset>';
}

// Adding a custom Metabox on WooCommerce single orders
add_action( 'add_meta_boxes', 'add_custom_shop_order_metabox' );
function add_custom_shop_order_metabox(){
add_meta_box(
'custom_shop_order_metabox',
__('Employee Extra Actions', 'woocommerce'),
'content_custom_shop_order_metabox',
'shop_order',
'side',
'core'
);
}

// Custom Metabox content on WooCommerce single orders
function content_custom_shop_order_metabox() {
global $thepostid, $post;

echo '<div class="options_group">';

woocommerce_wp_multi_checkbox( array(
'id' => 'employee_actions12',
'name' => 'employee_actions12[]',
'label' => __('Levels', 'woocommerce'),
'options' => array(
'tee' => __( 'MBO', 'woocommerce' ),
'saa' => __( 'HBO', 'woocommerce' ),
'tee1' => __( 'WO', 'woocommerce' ),
),
) );

echo '</div>';
}

// Save WooCommerce single orders Custom Metabox field values
add_action( 'save_post_shop_order', 'save_custom_shop_order_metabox_field_values' );
function save_custom_shop_order_metabox_field_values( $post_id ){
if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
|| ! current_user_can( 'edit_shop_order', $post_id ) ) {
return;
}

if( isset( $_POST['employee_actions12'] ) ){
update_post_meta( $post_id, 'employee_actions12', wc_clean($_POST['employee_actions12']) );
}
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Add a checkbox to show/hide checkout fields and display the values ​in WooCommerce backend

Besides the fact that you use new_billing_field and _new_billing_field interchangeably (note the underscore), do you not have code to effectively save the values ​​from the fields, before you can display them in other locations.

So you get:

function action_woocommerce_before_checkout_form() {
?>
<style>
p#new_billing_field_field.on { display:none !important; }
p#new_billing_field2_field.on { display:none !important; }
p#new_billing_field3_field.on { display:none !important; }
</style>

<script type="text/javascript">
jQuery(function($){
var a = 'input#checkbox_trigger';
var b = '#new_billing_field_field,#new_billing_field2_field,#new_billing_field3_field';

$(a).change(function() {
if ( $(this).prop('checked') === true && $(b).hasClass('on') ) {
$(b).show(function(){
$(b).css({'display':'none'}).removeClass('on').show();
});
}
else if ( $(this).prop('checked') !== true && ! $(b).hasClass('on') ) {
$(b).fadeOut(function(){
$(b).addClass('on')
});
$(b+' input').val('');
}
});
});
</script>
<?php
}
add_action( 'woocommerce_before_checkout_form', 'action_woocommerce_before_checkout_form' );

function filter_woocommerce_checkout_fields( $fields ) {
$fields['billing']['checkbox_trigger'] = array(
'type' => 'checkbox',
'label' => __( 'Ostan ettevõttena', 'woocommerce' ),
'class' => array( 'form-row-wide' ),
'clear' => true
);

$fields['billing']['new_billing_field'] = array(
'label' => __( 'Ettevõtte nimi', 'woocommerce' ),
'placeholder' => _x( 'Ettevõtte nimi', 'placeholder', 'woocommerce' ),
'class' => array( 'form-row-wide on' ),
'clear' => true
);

$fields['billing']['new_billing_field2'] = array(
'label' => __( 'Ettevõtte registrikood ', 'woocommerce' ),
'placeholder' => _x( 'Ettevõtte registrikood ', 'placeholder', 'woocommerce' ),
'class' => array( 'form-row-wide on' ),
'clear' => true
);
$fields['billing']['new_billing_field3'] = array(
'label' => __( 'Ettevõtte aadress', 'woocommerce' ),
'placeholder' => _x( 'Ettevõtte aadress', 'placeholder', 'woocommerce' ),
'class' => array( 'form-row-wide on' ),
'clear' => true
);

return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'filter_woocommerce_checkout_fields', 10, 1 );

// Save fields
function action_woocommerce_checkout_create_order( $order, $data ) {
// Isset and NOT empty, save
if ( isset( $_POST['new_billing_field'] ) && ! empty( $_POST['new_billing_field'] ) ) {
// Update meta data
$order->update_meta_data( '_new_billing_field', sanitize_text_field( $_POST['new_billing_field'] ) );
}

if ( isset( $_POST['new_billing_field2'] ) && ! empty( $_POST['new_billing_field2'] ) ) {
// Update meta data
$order->update_meta_data( '_new_billing_field2', sanitize_text_field( $_POST['new_billing_field2'] ) );
}

if ( isset( $_POST['new_billing_field3'] ) && ! empty( $_POST['new_billing_field3'] ) ) {
// Update meta data
$order->update_meta_data( '_new_billing_field3', sanitize_text_field( $_POST['new_billing_field3'] ) );
}
}
add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );

// Display field values on admin order pages after billing adress
function action_woocommerce_admin_order_data_after_billing_address( $order ) {
// Get meta
$new_billing_field = $order->get_meta( '_new_billing_field' );

// NOT empty
if ( ! empty ( $new_billing_field ) ) {
echo '<p><strong>' . __( 'Ostan ettevõttena', 'woocommerce' ) . ':</strong> ' . $new_billing_field . '</p>';
}

// Get meta
$new_billing_field2 = $order->get_meta( '_new_billing_field2' );

// NOT empty
if ( ! empty ( $new_billing_field2 ) ) {
echo '<p><strong>' . __( 'Ettevõtte aadress', 'woocommerce' ) . ':</strong> ' . $new_billing_field2 . '</p>';
}

// Get meta
$new_billing_field3 = $order->get_meta( '_new_billing_field3' );

// NOT empty
if ( ! empty ( $new_billing_field3 ) ) {
echo '<p><strong>' . __( 'Competitor dob day', 'woocommerce' ) . ':</strong> ' . $new_billing_field3 . '</p>';
}
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'action_woocommerce_admin_order_data_after_billing_address', 10, 1 );

WooCommerce admin product custom checkbox field not saving value

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.

Add extra checkboxes in Woocommerce user register form and saving / showing if are checked in the backend as user extra data

There is a mistake in your first function as each checkbox needs it own $key to be saved.

Here is your revisited code that will first validate that mandatory checkboxes, save values and display them in the admin User dashboard:

function registration_custom_checkboxes() {
return apply_filters( 'woocommerce_forms_field', array(
'age_ckeck' => array(
'type' => 'checkbox',
'label' => __("Soy mayor de 18", "woocommerce"),
'required' => true,
),
'permission_ckeck' => array(
'type' => 'checkbox',
'label' => __("Le doy permiso de usar mis datos", "woocommerce"),
'required' => true,
)
) );
}

// Display checkboxes in Registration form
add_action( 'woocommerce_register_form', 'add_registration_custom_checkboxes', 15 );
function add_registration_custom_checkboxes() {
foreach ( registration_custom_checkboxes() as $field_key => $field_args ) {
woocommerce_form_field( $field_key, $field_args );
}
}
// Validation for mandatory checkboxes in Registration form
add_action( 'woocommerce_register_post', 'registration_custom_checkboxes_validation', 10, 3 );
function registration_custom_checkboxes_validation( $username, $email, $validation_errors ) {
$fields = registration_custom_checkboxes();
foreach ( array_keys($fields) as $field_key ) {
if ( ! isset( $_POST[$field_key] ) {
if ( $field_key === 'age_ckeck' ) {
$validation_errors->add( $field_key . '_error', __("You need to approve that your are at leats 18 years old.", "woocommerce") );
} else {
$validation_errors->add( $field_key . '_error', __("You have to allow us to use your data.", "woocommerce") );
}
}
}
return $validation_errors;
}

// Save registration checkboxes fields values
add_action( 'woocommerce_created_customer', 'save_registration_custom_checkboxes_values' );
function save_registration_custom_checkboxes_values( $customer_id ) {
$fields = registration_custom_checkboxes();
foreach ( array_keys($fields) as $field_key ) {
if ( isset( $_POST[$field_key] ) ) {
update_user_meta( $customer_id, $field_key, '1' );
}
}
}

// Admin WP User: Display checkboxes fields on user profile
add_action ( 'show_user_profile', 'display_user_custom_checkboxes_fields' );
add_action ( 'edit_user_profile', 'display_user_custom_checkboxes_fields' );
function display_user_custom_checkboxes_fields( $user ){
echo '<h3>'.__("Age and permission checks", "woocommerce").'</h3>';
foreach ( registration_custom_checkboxes() as $field_key => $field_args ) {
woocommerce_form_field( $field_key, $field_args, get_user_meta( $user->id, $field_key, true ) );
}
}

// Admin WP User: Update checkboxes fields values
add_action( 'personal_options_update', 'save_user_custom_checkboxes_values' );
add_action( 'edit_user_profile_update', 'save_user_custom_checkboxes_values' );
function save_user_custom_checkboxes_values( $user_id ) {
$fields = registration_custom_checkboxes();
foreach ( array_keys($fields) as $field_key ) {
$value = isset( $_POST[$field_key] ) ? '1' : '0';
update_user_meta( $user_id, $field_key, $value );
// error_log( ('Key: ' . $field_key . ' | posted: ' . $_POST[$field_key] . ' | value: ' . $value) );
}
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Add checkbox to product inventory tab in WooCommerce and have the checkbox checked by default

woocommerce_admin_process_product_object replaces the outdated woocommerce_process_product_meta hook so you should definitely not replace it with it

To have the checkbox checked by default you can add value to the args from woocommerce_wp_checkbox()

So you get:

// Add checkbox
function action_woocommerce_product_options_inventory_product_data() {
global $product_object;

// Get meta
$value = $product_object->get_meta( '_cutom_meta_key' );

// Checkbox
woocommerce_wp_checkbox( array(
'id' => '_cutom_meta_key', // Required, it's the meta_key for storing the value (is checked or not)
'label' => __( 'Custom label', 'woocommerce' ), // Text in the editor label
'desc_tip' => false, // true or false, show description directly or as tooltip
'description' => __( 'Enable this to make something', 'woocommerce' ), // Provide something useful here
'value' => empty( $value ) ? 'yes' : $value // Checked by default
) );
}
add_action( 'woocommerce_product_options_inventory_product_data', 'action_woocommerce_product_options_inventory_product_data', 10, 0 );

// Save Field
function action_woocommerce_admin_process_product_object( $product ) {
// Update meta
$product->update_meta_data( '_cutom_meta_key', isset( $_POST['_cutom_meta_key'] ) ? 'yes' : 'no' );
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );


Related Topics



Leave a reply



Submit