Skip to content

Instantly share code, notes, and snippets.

@wpmudev-sls
Last active July 6, 2023 09:00
Show Gist options
  • Save wpmudev-sls/7915e5647920809a32af9bcc4b1e506a to your computer and use it in GitHub Desktop.
Save wpmudev-sls/7915e5647920809a32af9bcc4b1e506a to your computer and use it in GitHub Desktop.
[Forminator] - Auto populate fields with usermeta.
<?php
/**
* Plugin Name: [Forminator] - Auto populate fields with usermeta.
* Plugin URI: https://premium.wpmudev.org/
* Description: Autopopulate Forminator fields with usermeta.
* Author: Panos Lyrakis, Prashant Singh @ WPMUDEV
* Author URI: https://premium.wpmudev.org/
* License: GPLv2 or later
*/
if ( ! defined( 'ABSPATH' ) || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
return;
}
if ( ! class_exists( 'WPMUDEV_Forminator_AutoPopulate_Usermeta' ) ) {
class WPMUDEV_Forminator_AutoPopulate_Usermeta {
private static $_instance = null;
private $current_user = null;
public static function get_instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new WPMUDEV_Forminator_AutoPopulate_Usermeta();
}
return self::$_instance;
}
private function __construct() {
if ( is_user_logged_in() ) {
$this->current_user = get_current_user_id();
add_action( 'forminator_before_field_render', array( $this, 'prepare_prefill' ) );
add_filter( 'forminator_custom_form_submit_errors', array( $this, 'update_user_meta' ), 10, 3 );
}
}
public function update_user_meta( $submit_errors, $form_id, $field_data_array ) {
if ( empty( $submit_errors ) && ! is_null( $this->current_user ) ) {
$form = Forminator_Form_Model::model()->load( $form_id );
foreach ( $field_data_array as $field_data ) {
if ( ! isset( $field_data['name'] ) || ! isset( $field_data['value'] ) ) {
continue;
}
$field = $form->get_field( $field_data['name'] );
$prefill_key = sanitize_text_field( Forminator_Field::get_property( 'prefill', $field ) );
if ( ! empty( $prefill_key ) ) {
update_user_meta( (int) $this->current_user, $prefill_key, sanitize_text_field( $field_data['value'] ) );
}
}
}
return $submit_errors;
}
public function prepare_prefill( $field ) {
$prefill_key = sanitize_text_field( Forminator_Field::get_property( 'prefill', $field ) );
if ( ! empty( $prefill_key ) && ! is_null( $this->current_user ) && ! isset( $_REQUEST[ $prefill_key ] ) ) {
$meta_value = get_user_meta( (int) $this->current_user, $prefill_key, true );
if ( ! empty( $meta_value ) ) {
$_REQUEST[ $prefill_key ] = $meta_value;
}
}
}
}
if ( ! function_exists( 'wpmudev_forminator_autopopulate_usermate' ) ) {
function wpmudev_forminator_autopopulate_usermate() {
return WPMUDEV_Forminator_AutoPopulate_Usermeta::get_instance();
}
add_action( 'plugins_loaded', 'wpmudev_forminator_autopopulate_usermate', 10 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment