Question:
With Elementor and Elementor Pro it is possible to create forms for pages. They can consist of different types of fields, for example: radio button, checkbox, input and off course the select list with options.
In the editor of Elementor Pro it is very easy to add one or more options. But the problem is that this are static options. In the current version of Elementor Pro 3.23 it is not possible to add options on a dynamic way by executing a database query or WordPress shortcode.
How can you fill a select list dynamically with options?
Answer:
I want to create a select list that is filled with the same categories you can choose in the wp-admin environment when adding a post. Because categories can change in the future I have created the PHP script you can see below.
Where do you add this code?
You can add this to the functions.php file of your child theme or to a custom plugin when you have one.
Is this code executed in Elementor?
I have added a simple IF statement that prevent that the code will be executed when you edit the form in Elementor. Whitout this the code cause a strange fatal error. The code will be executed when you visit the page where the form is shown.
How does this code work?
When a select list will be genereated, the filter “elementor_pro/forms/render/item/select” will be executed. In the code I will check if the custom_id of the field equals ‘category’. The custom_id is the name of the field you can add in Elementor when editing the form.
If so, then I execute get_terms() and add the category names to an new array called $items. If there are any items found I will add those to the field options. When there are no items found I will show a simple error message.
Why do I use “\r\n” in implode()?
Elementor Pro forms select list only understand multiple options when you add them on a new line. That’s why I use “\r\n”. Double quotes are needed. With single quotes it will be processed as a string and all options will be shown as one option.
add_filter( 'elementor_pro/forms/render/item/select', function( $item, $index, $form ) { if (!\Elementor\Plugin::$instance->editor->is_edit_mode() && !\Elementor\Plugin::$instance->preview->is_preview_mode()) { if ('category' === $item['custom_id']) { $terms = get_terms(['taxonomy' => 'category', 'hide_empty' => false]); foreach ($terms as $term) { $items[] = $term->name; } // Add new options to the select list and overwrite the old ones. if (isset($items) && count($items) > 0) { // Elementor wants that options are added on a new line, thats why we ulse \r\n, double quotes are important. $item['field_options'] = implode("\r\n", $items); } else { $item['field_options'] = 'No items'; } } } return $item; }, 10, 3 );
> Check my other Dutch blogs about Elementor
Tested on:
WordPress 6.6.1 with Elementor 3.23.2 and Elementor Pro 3.23.1