当前位置:奉上博客 » 站长之家 » 正文

WordPress强化-网站纯代码如何实现倒计时功能

首先复制下面的代码,另存为“countdownjs.js”,放到你主题的js文件下。

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);
 
}

复制下列代码,加入主题的function.php中 (注意倒数第二行的js文件路径,根据你主题的情况更改。

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 '
		
活动倒计时:
		'.$day.'天
		'.$hour.'时
		'.$min.'分
		'.$sect.'秒
		
 
		
		';
	}else{
		return $content;
	}
}
 
add_shortcode('countdown', 'Brain_countdown');
wp_register_script( 'Brain_countdown_head_JS', get_template_directory_uri() . '/assets/js/countdownjs.js', array(), '1.0', false );
wp_enqueue_script( 'Brain_countdown_head_JS' );

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

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

相关文章