Created
August 13, 2020 11:10
-
-
Save techjewel/39e43c620f8ca59223c983893c1736cd to your computer and use it in GitHub Desktop.
Get product number and lookup in google sheet and then redirect the user to the target product url.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Catch submission the before it's inserting in database | |
* if you want to log the data in the database use hook: fluenform_before_submission_confirmation | |
*/ | |
add_action('fluentform_before_insert_submission', function ($insertData, $data, $form) { | |
if($form->id != 156) { // 156 is our target form id | |
return; | |
} | |
$csvUrl = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRENwqlrjjveVU-E-LANfPiMIsuTvdXqVVd0FGKTldEyrPnmF_tsjOYeV-4Q-qh5qqH9-NpYN44FH4r/pub?gid=0&single=true&output=csv'; | |
$matchedColumnIndex = 0; // 0 is the first column of the csv | |
$inputName = 'product_id'; // 'product_id' is the name attribute of the input | |
$row = ffeGetMatchedRow($csvUrl, $data[$inputName], $matchedColumnIndex); | |
if(!$row) { | |
// We could not find the product so send an error message | |
wp_send_json(['errors' => [ | |
$inputName => ['Sorry! No Product Found with this number'] | |
]], 422); | |
} | |
$productUrl = $row[1]; // We have product URL at the 2nd column so index is 1; | |
if(!$productUrl || filter_var($productUrl, FILTER_VALIDATE_URL) === FALSE) { | |
// Not a valid URL | |
wp_send_json(['errors' => [ | |
$inputName => ['Sorry! No Valid Product URL found'] | |
]], 422); | |
} | |
wp_send_json_success([ | |
'result' => [ | |
'redirectUrl' => $productUrl, | |
'message' => 'You are redirecting to the product page', | |
] | |
], 200); | |
}, 10,3); | |
/* | |
* Helper function will return the matched column value for the provided csv url | |
* Please note, You need Fluent Forms Pro to make it work | |
*/ | |
function ffeGetMatchedRow($csvUrl, $value, $columnIndex) | |
{ | |
if (!class_exists('CSVParser')) { | |
require_once(FLUENTFORMPRO_DIR_PATH . 'libs/CSVParser/CSVParser.php'); | |
} | |
$csvParser = new \CSVParser; | |
$content = file_get_contents($csvUrl); | |
$csvParser->load_data($content); | |
$rows = $csvParser->parse($csvParser->find_delimiter()); | |
if(!$rows) { | |
return false; | |
} | |
array_shift($rows); // remove the first item | |
foreach ($rows as $row) { | |
if(!empty($row[$columnIndex]) && $row[$columnIndex] == $value) { | |
return $row; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment