Skip to content

Instantly share code, notes, and snippets.

@wpmudev-sls
Last active December 14, 2021 11:05
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/e8b9d1646bad1af0202ff3e793e69193 to your computer and use it in GitHub Desktop.
Save wpmudev-sls/e8b9d1646bad1af0202ff3e793e69193 to your computer and use it in GitHub Desktop.
[Forminator Pro] - Name field custom prefixes
<?php
/**
* Plugin Name: [Forminator Pro] - Name field custom prefixes
* Plugin URI: https://premium.wpmudev.org/
* Description: Add custom prefixes on name field (as of 1.11.4)
* Author: Alessandro Kaounas @ WPMUDEV
* Author URI: https://premium.wpmudev.org/
* Task: 0/11289012348292/1165769246258511
* 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_Custom_Name_Prefixes' ) ) {
class WPMUDEV_Forminator_Custom_Name_Prefixes {
// Form ID to apply
private $form_id = 488;
// Pre selected custom prefix
private $selected = 'Parent';
// Custom prefixes to append
private $prefixes = array(
'Parent' => 'Parent',
'Child' => 'Child',
'Grandchild' => 'Grandchild',
);
// Append new values or override
private $append = true;
private static $_instance = null;
public static function get_instance() {
if( is_null( self::$_instance ) ){
self::$_instance = new WPMUDEV_Forminator_Custom_Name_Prefixes();
}
return self::$_instance;
}
private function __construct() {
if ( ! class_exists( 'Forminator' ) ) {
return;
}
$this->init();
}
private function init(){
add_filter( 'forminator_before_form_render', function( $id ){
if( $this->form_id !== $id ){
return;
}
// Add field filters
add_filter( 'forminator_name_prefixes', array( $this, 'wpmudev_forminator_name_prefixes' ) );
add_filter( 'forminator_field_markup', array( $this, 'wpmudev_forminator_field_markup' ), 10, 3 );
});
}
public function wpmudev_forminator_name_prefixes( $prefixes ){
if( ! $this->append ){
$prefixes = array();
}
foreach( $this->prefixes as $key => $value ){
$prefixes[$key] = __( $value, 'forminator' );
}
return $prefixes;
}
public function wpmudev_forminator_field_markup( $html, $field, $form ){
if( $field['type'] === 'name' && $field['element_id'] === 'name-1' ){
$field['prefix_placeholder'] = $this->selected;
// Remove any pre-selected prefix
$html = str_replace( ' selected="selected"', '', $html );
// Pre select new option
$html = str_replace( '<option value="' . $field['prefix_placeholder'] . '"', '<option value="' . $field['prefix_placeholder'] . '" selected="selected"', $html );
}
return $html;
}
}
add_action( 'plugins_loaded', function() {
return WPMUDEV_Forminator_Custom_Name_Prefixes::get_instance();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment