Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirejordansmith/be63d7d160184fecb82bd70fa395909d to your computer and use it in GitHub Desktop.
Save hirejordansmith/be63d7d160184fecb82bd70fa395909d to your computer and use it in GitHub Desktop.
Pre-populate a Gravity Forms Dropdown field with AffiliateWP Affiliates
<?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