今天就给大家转载分享一个纯代码的办法来为 WordPress 站点添加倒计时。
纯代码添加倒计时到 WordPress 站点步骤
1、把下面的代码保存为 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= '本次活动已经结束' } } |
2、把下面的代码添加到当前主题的 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() . '/js/countdownjs.js' , array (), '1.0' , false ); wp_enqueue_script( 'countdown_js' ); |
3、在发布/更新文章的时候,切换到文末模式,然后在想要插入倒计时的位置添加以下短代码:
[countdown time= "2019-01-15 18:41:57" ] |
其中 time="2019-01-15 18:41:57"引号中的时间就是活动结束时间,修改为其他日期时间时请保持格式一致即可。
小结
这个纯代码为 WordPress 站点添加倒计时还是非常简单易用的,只需要添加好 JS 文件和代码后,想添加倒计时就通过短代码来实现即可。如果担心忘记,我们还可以将倒计时的短代码集成到编辑器中。文章中的代码只是一种思路,倒计时的样式并没有美化,建议有需要的站长结合自己的主题来进行 DIY 会更好。