add a select field to gravity form prepopulated with the title from a custom post type called books

WordPress AI Code Robot

Create WordPress code snippets for free without a developer!

Jane requested the  following code from my WordPress AI Code Generator.

add a select field to gravity form prepopulated with the title from a custom post type called books

The robot generated the following code:

Sure, here's an example of how you could do this in your `functions.php` or your plugin file:

“`php
add_filter('gform_pre_render', 'nm_populate_book_titles');
add_filter('gform_pre_validation', 'nm_populate_book_titles');
add_filter('gform_pre_submission_filter', 'nm_populate_book_titles');
add_filter('gform_admin_pre_render', 'nm_populate_book_titles');

function nm_populate_book_titles($form){
foreach ($form['fields'] as &$field) {
// Assuming the field id is 1. Replace 1 with your actual field id.
if ($field->type != 'select' || strpos($field->cssClass, 'select-books') === false) {
continue;
}
$posts = get_posts('numberposts=-1&post_status=publish&post_type=books');
$choices = array();
foreach ($posts as $post) {
$choices[] = array('text' => $post->post_title, 'value' => $post->post_title);
}
$field->choices = $choices;
}
return $form;
}

“`

In this snippet, we're adding a filter to Gravity Forms render process which checks all the fields for one with a CSS class of `select-books` (you would add this class to the desired field in Gravity Forms), and if it finds it, it populates the choices with the titles of all published `Books` posts.

Please replace `'select-books'` with the actual css class you use at your gravity from select field.Also, replace `$field->type != 'select'` check with the appropriate one if the 'books' field is of different type other than 'select'.

More
CODE SNIPPETS