以下是我使用 Joshua David Nelson 创建的一小段代码填充 GravityForms 下拉列表的方法,josh@joshuadnelson.com
通过一些小的修改,我能够在下拉框中得到正确的输出(正在寻找用户电子邮件地址而不是用户昵称,但是您可以修改此脚本以输出任何您想要的内容,只需对查询参数)
// Gravity Forms User Populate, update the '1' to the ID of your form
add_filter( 'gform_pre_render_1', 'populate_user_email_list' );
function populate_user_email_list( $form ){
// Add filter to fields, populate the list
foreach( $form['fields'] as &$field ) {
// If the field is not a dropdown and not the specific class, move onto the next one
// This acts as a quick means to filter arguments until we find the one we want
if( $field['type'] !== 'select' || strpos($field['cssClass'], 'your-field-class') === false )
continue;
// The first, "select" option
$choices = array( array( 'text' => 'Just Send it to the Default Email', 'value' => 'me@mysite.com' ) );
// Collect user information
// prepare arguments
$args = array(
// order results by user_nicename
'orderby' => 'user_email',
// Return the fields we desire
'fields' => array( 'id', 'display_name', 'user_email' ),
);
// Create the WP_User_Query object
$wp_user_query = new WP_User_Query( $args );
// Get the results
$users = $wp_user_query->get_results();
//print_r( $users );
// Check for results
if ( !empty( $users ) ) {
foreach ( $users as $user ){
// Make sure the user has an email address, safeguard against users can be imported without email addresses
// Also, make sure the user is at least able to edit posts (i.e., not a subscriber). Look at: http://codex.wordpress.org/Roles_and_Capabilities for more ideas
if( !empty( $user->user_email ) && user_can( $user->id, 'edit_posts' ) ) {
// add users to select options
$choices[] = array(
'text' => $user->user_email,
'value' => $user->id,
);
}
}
}
$field['choices'] = $choices;
}
return $form;
}
/* end of populate advisors for dropdown field */
要使其正常工作,您只需将上述代码添加到您的 functions.php 文件中,添加您要更改的 GravityForm 的“ID”(到 add_filter 引用中)并添加您的下拉字段的“类”(其中显示“您的字段类”)。
如果您对上述代码有任何疑问,请告诉我。
亚当