纯代码实现WordPress主题添加倒计时功能

有些WordPress搭建的站点会发布一些限时活动或者限时的营销,仅仅在页面写上结束日期并不是很明了,因为搜索引擎上的内容会一直存在,所以可能会给某些访客造成误导,今天给大家带来的是纯代码实现WordPress主题添加倒计时功能!

[countdown time=”2021-06-13 22:00:00″]

其实很简单,就是给当前主题添加一段JS代码和一段函数即可轻松实现!

JS代码

将以下JS代码片段复制并保存为countdownjs.js,然后复制到主题当前目录下的js目录下:

function getAdd(time) {
	if (time < 10) {
		return "0" + time;
	} else {
		return time;
	}
}
var interval = 1000;

function ShowCountDown(year, month, day, hourd, minuted) {
	var now = new Date();
	var endDate = new Date(year, month - 1, day, hourd, minuted);
	var leftTime = endDate.getTime() - now.getTime();
	var leftsecond = parseInt(leftTime / 1000);
	var day = Math.floor(leftsecond / (60 * 60 * 24));
	day = day < 0 ? 0 : day;
	var hour = Math.floor((leftsecond - day * 24 * 60 * 60) / 3600);
	hour = hour < 0 ? 0 : hour;
	var minute = Math.floor((leftsecond - day * 24 * 60 * 60 - hour * 3600) / 60);
	minute = minute < 0 ? 0 : minute;
	var second = Math.floor(leftsecond - day * 24 * 60 * 60 - hour * 3600 - minute * 60);
	second = second < 0 ? 0 : second; var getDay = getAdd(day); var getHour = getAdd(hour); var getMinute = getAdd(minute); var getSecond = getAdd(second); if (endDate > now) {
		document.getElementById('time').innerHTML = '活动倒计时:';
		document.getElementById('day').innerHTML = getDay + '天';
		document.getElementById('hour').innerHTML = getHour + '时';
		document.getElementById('min').innerHTML = getMinute + '分';
		document.getElementById('sec').innerHTML = getSecond + '秒';
	} else {
		document.getElementById('countdown').innerHTML = '本次活动已经结束'
	}
}

PHP代码

将以下PHP代码复制到主题的functions.php

function countdown($atts, $content=null) {

extract(shortcode_atts(array("time" => ''), $atts));

date_default_timezone_set('PRC');

$endtime=strtotime($time);

$nowtime=time();

global $endtimes;

$endtimes = str_replace(array("-"," ",":"),",",$time);

if($endtime>$nowtime){

return '

<div id="countdown">

<span id="time"></span>

<span id="day"></span>

<span id="hour"></span>

<span id="min"></span>

<span id="sec"></span>

</div>

';

}else{

return '本次活动已经结束';

}

}

function countdown_js() {

global $endtimes;

echo '<script>window.setInterval(function(){ShowCountDown('.$endtimes.');},interval);</script>'."\n";

}

add_shortcode('countdown', 'countdown');

add_action('wp_footer', 'countdown_js');

wp_register_script( 'countdown_js', get_template_directory_uri() . '/assets/js/countdownjs.js', array(), '1.0', false );

wp_enqueue_script( 'countdown_js' );

 

代码调用

在需要显示倒计时的文章内容中添加以下代码即可,日期按照代码中的格式修改即可:

[countdown time=”2021-06-13 22:00:00″]
暂无评论

发送评论 编辑评论


				
上一篇
下一篇