Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alfredo-wpmudev/14df76aa7c029fd9e1b053722fdacd7a to your computer and use it in GitHub Desktop.
Save alfredo-wpmudev/14df76aa7c029fd9e1b053722fdacd7a to your computer and use it in GitHub Desktop.
Customizing Embed URL in hidden field using Javascript
<?php
/**
* Plugin Name: [Forminator Pro] - Hidden Field -> Embed URL replace with last URL path.
* Plugin URI: https://wpmudev.com/
* Description: Hidden Field -> Embed URL replace with last URL path.
* Author: Alfredo Galano Loyola @ WPMUDEV
* Author URI: https://wpmudev.com/
* 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_Hidden_Field_URL_Last_Path')) {
class WPMUDEV_Forminator_Hidden_Field_URL_Last_Path
{
/**
* $forms used to define the form and the hidden field that will be used. It's possible use the feature in several forms
* [forminator_form id="1049353"]
*/
private $forms = array(
1049353 => 'hidden-1',
);
private $form_id;
private static $_instance = null;
public static function get_instance()
{
if (is_null(self::$_instance)) {
self::$_instance = new WPMUDEV_Forminator_Hidden_Field_URL_Last_Path();
}
return self::$_instance;
}
private function __construct()
{
$this->init();
}
public function init()
{
// Do some checks here
if (!defined('FORMINATOR_VERSION') || FORMINATOR_VERSION < '1.12' || !class_exists('Forminator_API')) {
return;
}
add_action('wp_footer', array($this, 'customize_hidden_field_js'), 9999);
add_filter('forminator_render_form_markup', array($this, 'prepare_form_markup'), 1, 6);
}
public function customize_hidden_field_js()
{
if ( isset($this->forms[$this->form_id])){
?>
<script>
jQuery(document ).ready(function() {
form_id = "<?php echo $this->form_id;?>";
hidden_field = "<?php echo $this->forms[$this->form_id];?>";
let url = jQuery( `#forminator-module-${form_id} [name="${hidden_field}"]` ).val();
jQuery( `#forminator-module-${form_id} [name="${hidden_field}"]` ).val(get_last_past(url)).trigger('change');
function get_last_past(url){
let url_parts = url.split("/");
if(url_parts[url_parts.length-1] !== ""){
return url_parts[url_parts.length-1]
}
return url_parts[url_parts.length-2];
}
});
</script>
<?php
}
}
public function prepare_form_markup($html, $form_fields, $form_type, $form_settings, $form_design, $render_id)
{
if ('custom-form' != $form_type){
return $html;
}
$this->form_id = $form_settings['form_id'];
return $html;
}
}
add_action('plugins_loaded', function () {
return WPMUDEV_Forminator_Hidden_Field_URL_Last_Path::get_instance();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment