Skip to content

Instantly share code, notes, and snippets.

@alfredo-wpmudev
Last active June 14, 2023 00:34
Show Gist options
  • Save alfredo-wpmudev/5c4cf3b90a46408c80b73de56cee7305 to your computer and use it in GitHub Desktop.
Save alfredo-wpmudev/5c4cf3b90a46408c80b73de56cee7305 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: [Forminator Pro] - Bulk add options to a Select field
* Plugin URI: https://premium.wpmudev.org/
* Description: Load data from specific table on the Database and populating the select field.
* Author: Alessandro Kaounas @ WPMUDEV, Paweł Pela @ WPMUDEV, Alfredo Loyola @WPMUDEV
* Author URI: https://premium.wpmudev.org/
* License: GPLv2 or later
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// No need to do anything if the request is via WP-CLI.
if ( defined( 'WP_CLI' ) && WP_CLI ) {
return;
}
if ( ! class_exists( 'WPMUDEV_Forminator_Bulk_Select_Options' ) ) {
class WPMUDEV_Forminator_Bulk_Select_Options {
// User defined settings
//Set your Form ID here
private $form_id = 1048098;
//Indicate the select field that will receive the data
private $field_id = 'select-1';
// User defined options
private $options = array();
private static $_instance = null;
public static function get_instance() {
if( is_null( self::$_instance ) ){
self::$_instance = new WPMUDEV_Forminator_Bulk_Select_Options();
}
return self::$_instance;
}
private function __construct() {
/*Customize your data to load here */
global $wpdb;
$church_id = get_current_user_id();
$sql = $wpdb->prepare("SELECT DISTINCT id,Full_Name FROM AllPartners WHERE churchid=%d ORDER BY Full_Name ASC",$church_id);
$partners = $wpdb->get_results($sql);
foreach($partners as $partner) {
$this->options[$partner->id] = $partner->Full_Name;
}
/*Stop customizing */
if ( ! defined( 'FORMINATOR_VERSION' ) || FORMINATOR_VERSION < '1.12' ) {
return;
}
$this->init();
}
public function init(){
add_filter( 'forminator_before_form_render', array( $this, 'wpmudev_forminator_before_form_render' ) );
}
public function wpmudev_forminator_before_form_render( $id ){
if( $this->form_id != $id ){
return;
}
add_filter( 'forminator_field_markup', array( $this, 'wpmudev_forminator_field_markup' ), 10, 2 );
}
public function wpmudev_forminator_field_markup( $html, $field ){
if( $field['element_id'] === $this->field_id ){
$markup = '';
foreach( $this->options as $key => $option ){
$markup .= '<option value="' . $key . '" data-calculation="0">' . $option .'</option>';
}
$html = preg_replace('/<option.*<\/option>/m', '', $html);
return str_replace( '</select>', $markup . '</select>', $html );
}
return $html;
}
}
add_action( 'plugins_loaded', function(){
return WPMUDEV_Forminator_Bulk_Select_Options::get_instance();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment