我正在尝试从一段JavaScript代码创建一个简码,以便允许我在页面上的某个位置调用javascript。
javascript相对简单并且可以正常工作(显示倒数计时器)。但是,在尝试对它进行简码时,不会在前端正确调用它。
下面是我的步骤和代码生成...有关如何正确显示此代码的任何建议,将不胜感激!
date_counter
函数的Javascript代码:
// The Jquery script
add_action( 'wp_footer', 'date_counter' );
function date_counter() {
?>
<script>
// Set the date we're counting down to
var countDownDate = new Date("July 29, 2018 09:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
<?php
}
这是我要尝试将date_counter
函数初始化为短代码的PHP函数:
add_action( 'init', 'register_shortcodes');
function register_shortcodes(){
add_shortcode('datecountershortcode', 'date_counter');
}
这是我在wordpress页面上调用最终短代码以尝试显示计数器的方式
[datecountershortcode]
尝试调用上述简码不起作用,仅显示简码文本。有什么想法我想念的吗?
答案 0 :(得分:0)
添加简码时,您不想调用“ date_counter”。您正在使用javascript查找ID为“ demo”且ID为“ demo”的元素,因此您需要一个单独的shortcode函数,该函数会将其放在页面上。试试这个。
function datecountershortcode_func( $atts ) {
return '<div id="demo"></div>';
}
add_action( 'init', 'register_shortcodes');
function register_shortcodes(){
add_shortcode('datecountershortcode', 'datecountershortcode_func');
}