wordpress不用插件实现倒计时的功能

前面介绍了wordpress自定义样式倒计时插件jcountdown ,插件的话不受主题更换的影响,如何需要用代码实现的话,下面给大家分享不用插件如何实现倒计时功能。

第一步新增一个js文件 countdown.js,代码如下:

PHP
function ShowCountDown(prefix,year,month,day,hourd,minuted,seconded){
	var now = new Date();
	if( typeof(hourd) == "undefined" ) hourd=23;
	if( typeof(minuted) == "undefined" ) minuted=59;
	if( typeof(seconded) == "undefined" ) seconded=59;
	var endDate = new Date(year, month-1, day, hourd, minuted,seconded);
	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 day2 = (day<10?"0"+day:day);
	var hour2 = (hour<10?"0"+hour:hour);
	var minute2 = (minute<10?"0"+minute:minute);
	var second2 = (second<10?"0"+second:second);
 
	jQuery("#"+prefix+"_countDown_day").html(day);
	jQuery("#"+prefix+"_countDown_hour").html(hour2);
	jQuery("#"+prefix+"_countDown_min").html(minute2);
	jQuery("#"+prefix+"_countDown_sec").html(second2);
 
}

第二步在functions.php中加入下面代码,引用刚刚的js文件:

PHP
function Brain_countdown($atts, $content=null) {
	extract(shortcode_atts(array("time" => ''), $atts));
	extract(shortcode_atts(array("prefix" => ''), $atts));
	date_default_timezone_set('PRC');
	$endtime=strtotime($time);
	$nowtime=time();
	$counttime=$endtime-$nowtime;
	$day=floor($counttime/(60*60*24));
	$day=$day<10 ? "0".$day : $day;
	$hour=floor(($counttime-$day*24*60*60)/3600);
	$hour=$hour<10 ? "0".$hour : $hour;
	$min=floor(($counttime-$day*24*60*60-$hour*3600)/60);
	$min=$min<10 ? "0".$min : $min;
	$sect=floor($counttime-$day*24*60*60-$hour*3600-$min*60-1);
	$sect=$sect<10 ? "0".$sect : $sect; $endtimes = str_replace(array("-"," ",":"),",",$time); if($endtime>$nowtime){
		return '
<div class="countDownCont">活动倒计时: <span id="'.$prefix.'_countDown_day" style="left: 10px;">'.$day.'</span>天 <span id="'.$prefix.'_countDown_hour" style="left: 125px;">'.$hour.'</span>时 <span id="'.$prefix.'_countDown_min" style="left: 232px;">'.$min.'</span>分 <span id="'.$prefix.'_countDown_sec" style="left: 342px;">'.$sect.'</span>秒</div>
<script>window.setInterval(function(){ShowCountDown("'.$prefix.'" , '.$endtimes.' );}, 1000);</script> '; }else{ return $content; } } add_shortcode('countdown', 'Brain_countdown'); wp_register_script( 'Brain_countdown_head_JS', get_template_directory_uri() . '/js/countdown.js', array(), '1.0', false ); wp_enqueue_script( 'Brain_countdown_head_JS' );

 

调用方法:(去掉countdown 中间的“——”号。)

PHP
[count——down time='2018-7-10 20:30:30' prefix='pro1']活动已结束[/count——down]

显示效果如下:

wordpress不用插件实现倒计时的功能

上一篇:线程计数器countdownlatch和cyclicbarrier


下一篇:[FAQ] WPS 服务程序是一种流氓软件吗