Last active
January 1, 2024 08:28
-
-
Save wpmudev-sls/adb493e7154f135fdf04db883e18927a to your computer and use it in GitHub Desktop.
Plugin Name: [Forminator] - Auto populate fields with post id.
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 | |
/** | |
* Plugin Name: [Forminator] - Auto populate fields with post id. | |
* Plugin URI: https://premium.wpmudev.org/ | |
* Description: Autopopulate Forminator select field with current post id. | |
* Author: Panos Lyrakis @ WPMUDEV | |
* Author URI: https://premium.wpmudev.org/ | |
* License: GPLv2 or later | |
*/ | |
if ( ! defined( 'ABSPATH' ) || ( defined( 'WP_CLI' ) && WP_CLI ) ) { | |
return; | |
} | |
add_filter( | |
'forminator_cform_render_fields', | |
function( $wrappers, $model_id ) { | |
if ( 6 !== $model_id ) { // Please change the form ID. | |
return $wrappers; | |
} | |
$id = get_the_ID(); | |
if ( empty( $id ) ) { | |
$id = sanitize_text_field( $_POST['extra']['page_id'] ); | |
} | |
$select_field_id = 'select-1'; | |
$selected_options = array( | |
// post_id => options value | |
15 => 'one', | |
27 => 'two', | |
63 => 'Option-3', | |
); | |
if ( in_array( $id, array_keys( $selected_options ) ) ) { | |
$selected_value = $selected_options[ $id ]; | |
foreach ( $wrappers as $wrapper_key => $wrapper ) { | |
if ( ! isset( $wrapper['fields'] ) ) { | |
continue; | |
} | |
foreach ( $wrapper['fields'] as $wrapped_field_key => $wrapped_field ) { | |
$field_id = $wrapper['fields'][ $wrapped_field_key ]['element_id']; | |
if ( $select_field_id === $field_id && ! empty( $wrappers[ $wrapper_key ]['fields'][ $wrapped_field_key ]['options'] ) ) { | |
foreach( $wrappers[ $wrapper_key ]['fields'][ $wrapped_field_key ]['options'] as $option_key => $option ) { | |
if ( $selected_value === $wrappers[ $wrapper_key ]['fields'][ $wrapped_field_key ]['options'][ $option_key ]['value'] ) { | |
$wrappers[ $wrapper_key ]['fields'][ $wrapped_field_key ]['options'][ $option_key ]['default'] = true; | |
} else { | |
$wrappers[ $wrapper_key ]['fields'][ $wrapped_field_key ]['options'][ $option_key ]['default'] = false; | |
} | |
} | |
} | |
} | |
} | |
} | |
return $wrappers; | |
}, | |
10, | |
2 | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It seems not working on 1.26.