I’m having difficulties figuring out what filters or actions should I write when I want to keep any params (‘?ref={username}’) in my URLs when user is navigating through the site AND is redirected to another domain.
How do I always keep ‘?ref={username}’ param with every action link user clicks.
I cannot use add_query_var() , because if this is added, then user is redirected to /blog page, which is set up in my link permastructure for blogs/single posts/post templates/search/categories/pagination pages.
I found the following code can be used to extract the values and include, but it doesn’t seem to have any required effect.
It seems there’s a 2 part solution for this.
First, to detect any ref code in the URL and store the ref into cookies.
Then either use cookies ref value if it’s set to add filters for all the links to include the args or use javascript to add any link click event listener to include the ref, or both.
Following code below.
Detect ref from URL and store it in cookies, I added both scripts to the body (footer) :
<script>
// Function to get a cookie value
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
// Add event listener to all link buttons
document.querySelectorAll('a').forEach(function(link) {
link.addEventListener('click', function(event) {
event.preventDefault(); // Prevent the default action
var href = this.getAttribute('href');
var ref = getCookie('ref'); // Get 'ref' cookie value
if (ref) {
href += (href.indexOf('?') !== -1 ? '&' : '?') + 'ref=' + ref;
}
window.location.href = href; // Navigate to the new URL
});
});
</script>
Additionally for PHP if I want to carry on the ref value from cookies to every page to be visible,
I could use additional filters. But this is probably not necessary anymore as I already got the value stored in cookies. Just FYI if anyone’s looking into what filters to use.
add_filter(‘the_permalink’, ‘add_cookie_value_to_permalink’);
add_filter(‘page_link’, ‘add_cookie_value_to_permalink’);
add_filter(‘post_link’, ‘add_cookie_value_to_permalink’);
add_filter(‘term_link’, ‘add_cookie_value_to_permalink’);
add_filter(‘tag_link’, ‘add_cookie_value_to_permalink’);
add_filter(‘category_link’, ‘add_cookie_value_to_permalink’);
function add_cookie_value_to_permalink($url) {
// Check if the 'ref' cookie is set
if (isset($_COOKIE['ref'])) {
// Add the 'ref' cookie value as a parameter to the URL
$url = add_query_arg('ref', $_COOKIE['ref'], $url);
}
return $url;
}