Logo Gray

How to Store a Request Parameter as Cookie in WordPress

I wanted to store a Request Parameter as Cookie to access it from any Webpage within my site. To Accomplish that i inserted a litte schript into my WPCode Snippet Plugin, that inserts it to every header. After inserting the script, it is also possible to access the cookie using Elementor Pro

The cookie has the name: fname because that is also the parameter, the visitor had in the url, set by a Elementor form.

				
					
<!-- cookie script -->
<script>
// Funktion zum Lesen von Request-Parametern
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

// Funktion zum Erstellen eines Cookies
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

// Überprüfen, ob der Parameter "fname" im Request vorhanden ist
var nameParam = getParameterByName('fname');

// Überprüfen, ob bereits ein Cookie für "fname" vorhanden ist
var existingCookie = getParameterByName('fname', document.cookie);

// Wenn "nameParam" existiert und nicht mit dem Cookie übereinstimmt
if (nameParam && nameParam !== existingCookie) {
    // Cookie für "fname" setzen, das zwei Wochen lang gültig ist
    setCookie('fname', nameParam, 14);
}

</script>