SO网友:Brooke.
这个问题不是WordPress特有的,所以对于StackOverflow来说可能更好。我们可以通过建议使用wp_enqueue_script
将脚本添加到页面,但最终这是一个JavaScript问题。
我的回答是基于this article
// Get the local time of the visitor
var localTime = new Date();
var localHour = localTime.getHours();
// Bool to determine if it is night or day
var isNight = ( 18 <= localHour || 8 >= localHour ) ? true : false;
// Object containing URL links to images
const backgroundURLs = {
day: \'https://placekitten.com/1960/1960\',
night: \'https://placekitten.com/1961/1961\',
};
// Sets the background image
const setBackground = (image) => {
// wait for window to be loaded to ensure body is present,
// if you are checking this elsewhere you can remove the window.onload check
window.onload = function() {
document.body.style.background = "url(\'"+backgroundURLs[image]+"\')";
}
};
// Actually set the background based on the bool and URL object.
if ( isNight ) {
setBackground(\'night\');
} else {
setBackground(\'day\');
}