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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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.