Skip to content

Instantly share code, notes, and snippets.

@matty0501
Last active May 9, 2023 19:13
Show Gist options
  • Save matty0501/781dcdd5242bfd8117f48610add032ed to your computer and use it in GitHub Desktop.
Save matty0501/781dcdd5242bfd8117f48610add032ed to your computer and use it in GitHub Desktop.
<?php
/**
* Use this snippet to populate a Gravity Forms dropdown with years as choices, starting with the current year
* By default, the snippet will return four years, including the current year
* For example, the current year is 2023, so the dropdown choices would be 2023, 2024, 2025, 2026
* You will need to add the css class "populate-years" to the dropdown
*/
// Change 123 to your form ID
add_filter( 'gform_pre_render_123', 'populate_posts' );
add_filter( 'gform_pre_validation_123', 'populate_posts' );
add_filter( 'gform_pre_submission_filter_123', 'populate_posts' );
add_filter( 'gform_admin_pre_render_123', 'populate_posts' );
function populate_posts( $form ) {
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-years' ) === false ) {
continue;
}
$choices = array();
$i = 1;
$year = date("Y");
while ( $i <= 4 ) { // Change 4 to the number of years you wish to populate
$choices[] = array( 'text' => $year, 'value' => $year );
$year++;
$i++;
}
$field->choices = $choices;
}
return $form;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment