Last active
June 14, 2024 21:25
-
-
Save hirejordansmith/be63d7d160184fecb82bd70fa395909d to your computer and use it in GitHub Desktop.
Pre-populate a Gravity Forms Dropdown field with AffiliateWP Affiliates
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 | |
// Add filters for Form ID 8 | |
add_filter( 'gform_pre_render_8', 'populate_posts' ); | |
add_filter( 'gform_pre_validation_8', 'populate_posts' ); | |
add_filter( 'gform_pre_submission_filter_8', 'populate_posts' ); | |
add_filter( 'gform_admin_pre_render_8', 'populate_posts' ); | |
function populate_posts( $form ) { | |
// Loop through each field searching for any "select" field with the class "populate-affs" | |
foreach ( $form['fields'] as &$field ) { | |
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-affs' ) === false ) { | |
continue; | |
} | |
// Set arguments for an affiliates query | |
$args = array ( | |
'number' => -1, | |
'order' => 'ASC', | |
'orderby' => 'name' | |
); | |
// Get Affiliates | |
$affiliates = affiliate_wp()->affiliates->get_affiliates($args); | |
// Set empty choices array | |
$choices = array(); | |
// Loop through Affiliates and assign text (label) and value for each | |
foreach ($affiliates as $affiliate) { | |
// Set Affiliate ID as a variable | |
$affiliate_id = $affiliate->affiliate_id; | |
// Set User ID as a variable | |
$user_id = $affiliate->user_id; | |
// Get User Object with User ID | |
$user = get_user_by( 'id', $user_id ); | |
// Assign Users First Name as the option label | |
// Assign Affiliate ID as the option value | |
$choices[] = array( | |
'text' => $user->first_name, | |
'value' => $affiliate_id | |
//'isSelected' => $post->ID == rgget('post_id') | |
); | |
} | |
// update the Drop Down field placeholder | |
$field->placeholder = 'Select a Sales Rep'; | |
$field->choices = $choices; | |
} | |
return $form; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to create referee based on select id?