Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alfredo-wpmudev/80b19b2e3f259bd74f87b587b64b3998 to your computer and use it in GitHub Desktop.
Save alfredo-wpmudev/80b19b2e3f259bd74f87b587b64b3998 to your computer and use it in GitHub Desktop.
Customize Forminator Hidden Field -> Embed URL to only save the last path of the URL
<?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 $embed_url;
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_filter('forminator_custom_form_submit_field_data', array($this, 'wpmudev_set_field_data'), 10, 2);
}
//Working with the submitted Data
public function wpmudev_set_field_data($field_data_array, $form_id)
{
if (!in_array($form_id, array_keys($this->forms))) {
return $field_data_array;
}
foreach ($field_data_array as $key => $field){
if ($field['name'] === $this->forms[$form_id]) {
//Getting URL in the Hidden Field
$this->embed_url = $field['value'];
//Removing the Hidden Field
unset($field_data_array[$key]);
}
}
//Getting the last Path of the URL
$last_path = $this->get_embed_url_last_path($this->embed_url);
//Recreating the Hidden Field
$field_data_array[] = array(
'name' => $this->forms[$form_id],
'value' => $last_path,
'field_array' => array(
'default_value' => 'custom_value',
'custom_value' => $last_path,
)
);
return $field_data_array;
}
function get_embed_url_last_path($embed_url){
$url_parts = explode("/", $embed_url);
$linksArray = array_values(array_filter($url_parts));
return $linksArray[count($linksArray)-1];
}
}
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