Automatically retrieve fbclid value parameter from URL and store it in a cookie
The code below will hook into the WordPress initialization action, check if the ‘fbclid’ parameter is present in the URL, and if it is, it will create a cookie with its value. This function will be executed on the front-end for every page load.
Total Time Needed :
20
Minutes
Required Tools:
Things Needed?
To implement the feature of automatically retrieving the fbclid value from the URL and storing it in a cookie, follow these instructions:
Ensure you are working in a child theme to avoid updates to the parent theme overwriting your customizations.
Navigate to the child theme directory.
Edit the `functions.php` file within your child theme.
Copy and paste the complete PHP code snippet provided below at the end of the `functions.php` file.
Save the changes to the `functions.php` file.
Test the code on a testing or staging environment before deploying it to a live website to ensure it functions correctly.
Code
function wpdevai_set_fbclid_cookie() {
if (isset($_GET['fbclid'])) {
$fbclid = sanitize_text_field($_GET['fbclid']);
// Cookie will expire after 30 days
$cookie_duration = 30 * DAY_IN_SECONDS;
setcookie('wpdevai_fbclid', $fbclid, time() + $cookie_duration, COOKIEPATH, COOKIE_DOMAIN);
}
}