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.
Secondly, use javascript to add any link click event listener to include the ref.
Detect ref from URL and store it in cookies, I added both scripts to the body (footer) :
<script>
function storeRefInCookie() {
const urlParams = new URLSearchParams(window.location.search);
const ref = urlParams ? (urlParams.get('ref') || urlParams.get('r')) : null;
if (ref) {
const maxAge = 60 * 60 * 24 * 2; // 2 days
const cookieValue = ref + '; path=/;' + 'max-age=" + maxAge + ";' + 'SameSite=None; Secure;';
document.cookie="ref=" + cookieValue
document.cookie="referredByUser=" + cookieValue;
}
}
storeRefInCookie();
</script>
Add event listener
<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>
Also, if anyone is looking for what filters to use for WP user navigation to write some customizations, here”s the list (I didn’t need it):
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');