Skip to content

Instantly share code, notes, and snippets.

@jetsloth
Last active February 12, 2025 02:15
Show Gist options
  • Save jetsloth/2adc7557db426f8aec5872d31c8ec938 to your computer and use it in GitHub Desktop.
Save jetsloth/2adc7557db426f8aec5872d31c8ec938 to your computer and use it in GitHub Desktop.
Example of dynamic population for color picker options
<?php
add_filter( 'gform_pre_render', 'populate_gf_color_choices' );
add_filter( 'gform_pre_validation', 'populate_gf_color_choices' );
add_filter( 'gform_pre_submission_filter', 'populate_gf_color_choices' );
add_filter( 'gform_admin_pre_render', 'populate_gf_color_choices' );
function populate_gf_color_choices( $form ) {
$FORM_ID = 9999;
$FIELD_ID = 9999;
if ( rgar($form, 'id') != $FORM_ID ) {// set to the form id you want to run this on
return $form;
}
$posts_query = new WP_Query(array(
'post_type' => 'custom_post_type',
'meta_query' => array(
array(
'key' => 'feature_color',// meta field key
'compare' => 'EXISTS'
),
),
'posts_per_page' => -1,
'fields' => 'ids'
));
$choices = array();
$inputs = array();
$input_id = 1;
if ( !empty($posts_query->posts) ) {
foreach( $posts_query->posts as $post_id ) {
$color = get_post_meta( $post_id, 'feature_color', true );// get the meta field value
$choices[] = array(
'value' => $color,// set to whatever you want the "value" of the choice to be
'text' => $color,// set to whatever you want the "text" (label) of the choice to be
'colorPicker_color' => $color,// set to the color hex value (including #)
);
$inputs[] = array( 'label' => $choice['text'], 'id' => "{$field->id}.{$input_id}" );
$input_id++;
}
foreach ( $form['fields'] as &$field ) {
if ( $field->id == $FIELD_ID ) {
$field->colorPicker_enableColors = true;
$field->choices = $choices;
if ( $field->type == "checkbox" || $field->inputType == "checkbox" ) {
$field->inputs = $inputs;
}
}
}
}
return $form;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment