1. Home
  2. Knowledge Base
  3. WooCommerce Product Add-Ons Ultimate
  4. Enable a default value for checkbox groups
  1. Home
  2. Knowledge Base
  3. Checkbox Groups
  4. Enable a default value for checkbox groups

Enable a default value for checkbox groups

Checkbox groups can have more than one option selected, making it difficult to set a default value. However, you can use a snippet to achieve this.

Let’s say you have a checkbox group field with an ID of 999. You have three options in the checkbox group:

  • My first default option
  • My second default option
  • My third option

You want to set the first two options as default – so that they will automatically be selected when the user loads the product page.

You can use the following snippet. Note that you’ll need to edit it to ensure the correct field ID is used (not 999). Also, edit the options that you want to see entered as defaults.

<?php
/**
* Enable a default value for checkbox groups.
* Your default value must be an array.
* You'll need to change the value of the $field_id to match your own Field ID
* @param $value The current value of the field
* @param $id The field ID in the format pewc_group_888_999
* @param $field The field object
* @param $posted The $_POST object
*/
function prefix_default_field_value( $value, $id, $field, $posted ) {
// Change this to the ID of the field you are setting a default for
$field_id = 999;
// Don't overwrite a value that's already there
if( $value ) {
return $value;
}
// Now look for our Field ID
if( $field_id == $field['field_id'] ) {
// You need to enter the default values here, copied exactly from your checkbox group options
$value = array(
'My first default option',
'My second default option'
);
}
return $value;
}
add_filter( 'pewc_default_field_value', 'prefix_default_field_value', 10, 4 );

Here’s how to add a snippet.

Was this article helpful?

Related Articles