Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpmudev-sls/adb493e7154f135fdf04db883e18927a to your computer and use it in GitHub Desktop.
Save wpmudev-sls/adb493e7154f135fdf04db883e18927a to your computer and use it in GitHub Desktop.
Plugin Name: [Forminator] - Auto populate fields with post id.
<?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
);
@tennyy
Copy link

tennyy commented Dec 5, 2023

It seems not working on 1.26.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment