Skip to content

Instantly share code, notes, and snippets.

@goranefbl
Created September 7, 2024 15:45
Show Gist options
  • Save goranefbl/0e143b4fc9cd7bb46024a3347f96e290 to your computer and use it in GitHub Desktop.
Save goranefbl/0e143b4fc9cd7bb46024a3347f96e290 to your computer and use it in GitHub Desktop.
save UTM params
<?php
function save_source_tracker_meta($order_id)
{
$disabled = get_option('wpgens_st_disable');
if ($disabled) {
return;
}
$last_touch = isset($_COOKIE['wpg_last']) ? json_decode(stripslashes($_COOKIE['wpg_last']), true) : null;
$first_touch = isset($_COOKIE['wpg_first']) ? json_decode(stripslashes($_COOKIE['wpg_first']), true) : null;
$unique_id = isset($_COOKIE['wpg_id']) ? sanitize_text_field($_COOKIE['wpg_id']) : null;
if (!$last_touch && !$first_touch) {
return;
}
$data_to_save = WPGens_ST\Includes\WPGens_ST_Config::getDataToSave();
$order = wc_get_order($order_id);
if ($unique_id) {
$order->update_meta_data('_wpg_id', $unique_id);
}
if ($last_touch) {
$last_touch = $this->sanitize_array($last_touch);
$order->update_meta_data('wpg_last', $last_touch);
foreach ($data_to_save as $key) {
if (isset($last_touch[$key]) && $last_touch[$key] !== '') {
$order->update_meta_data('_wpg_last_' . $key, $last_touch[$key]);
}
}
// Extract and save click identifiers from the URL
if (isset($last_touch['url'])) {
$url_components = parse_url($last_touch['url']);
if (isset($url_components['query'])) {
parse_str($url_components['query'], $params);
$click_ids = ['gclid', 'fbclid', 'msclkid'];
foreach ($click_ids as $id) {
if (isset($params[$id])) {
$order->update_meta_data('_wpg_last_' . $id, sanitize_text_field($params[$id]));
}
}
}
}
}
if ($first_touch) {
$first_touch = $this->sanitize_array($first_touch);
$order->update_meta_data('wpg_first', $first_touch);
foreach ($data_to_save as $key) {
if (isset($first_touch[$key]) && $first_touch[$key] !== '') {
$order->update_meta_data('_wpg_first_' . $key, $first_touch[$key]);
}
}
// Extract and save click identifiers from the URL
if (isset($first_touch['url'])) {
$url_components = parse_url($first_touch['url']);
if (isset($url_components['query'])) {
parse_str($url_components['query'], $params);
$click_ids = ['gclid', 'fbclid', 'msclkid'];
foreach ($click_ids as $id) {
if (isset($params[$id])) {
$order->update_meta_data('_wpg_first_' . $id, sanitize_text_field($params[$id]));
}
}
}
}
}
$order->save();
return $order_id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment