1. Home
  2. Knowledge Base
  3. WooCommerce Product Add-Ons Ultimate
  4. Product Page
  5. Auto-populate field value
  1. Home
  2. Knowledge Base
  3. WooCommerce Product Add-Ons Ultimate
  4. Auto-populate field value

Auto-populate field value

You can pre-populate a field value, e.g. through a parameter in the URL, by using the pewc_default_field_value filter.

In the example below, we can load a product page with a URL that includes the parameter ?my_param=abc.

The snippet looks for the my_param parameter and checks the field ID. If the my_param parameter is present and the field ID matches, then the field will be populated with the value of the parameter, in this case ‘abc’.

You’ll need to update the field ID in the snippet to match the field you want to pre-populate.

<?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_set_field_value_by_url_param( $value, $id, $field, $posted ) {
// Change this to the ID of the field you are setting a default for
$field_id = 8018;
// Don't overwrite a value that's already there
if( isset( $_GET['my_param'] ) && $field_id == $field['field_id'] ) {
$value = esc_attr( $_GET['my_param'] );
}
return $value;
}
add_filter( 'pewc_default_field_value', 'prefix_set_field_value_by_url_param', 10, 4 );

You can see how to add a snippet here.

Was this article helpful?

Related Articles