Osiyo. Dohiju? Hey, welcome back.
I’m throwing this out here. I needed a quick script to redirect users on the front-end. I wanted to be able to implement it without messing with the webserver. The idea is that the script looks at the url – which contains unique values for the pages I want to redirect to start with. Each page needs to be unlocked at a specific time and day. If I append a query string parameter that reads “nope” then it won’t redirect so I can edit the page. This isn’t exactly how I’m making it happen – I wanted something to illustrate the behavior.
Basically, I set up a map to contain all of the url pieces I want to test for and then the Date object that contains the relevant data to skip redirecting for that page. Then the code loops through the map checking the url for the url fragments and if it finds it then it checks to see if the current Date is less than the Date it’s supposed to be accessible.
Again, I would normally do this with redirects elsewhere like the webserver. However, this works great for putting at the top of wordpress code. I know there are many other ways to accomplish this – I chose the fastest implementation for me.
Until next time. Dodadagohvi.
var map = new Map();
function createDate(day, hour, minute) {
var d = new Date();
d.setDate(day);
d.setMonth(6);
d.setFullYear(2020);
d.setMinutes(minute);
d.setHours(hour);
return d;
}
map.set('myUrlHere', createDate(17, 10, 0));
function countDown() {
var urlHref = window.location.href;
if (urlHref.indexOf("nope") > -1) {
return;
}
map.forEach(function logMapElements(value, key, map) {
if (urlHref.indexOf(key) > -1) {
if (new Date() < value) {
window.location.replace("http://mydomainname.com/stay-tuned/");
}
}
});
}
countDown();