WordPress从javascript功能创建简码



我正在尝试从一段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]

尝试调用上述短代码不起作用,仅显示短代码文本。知道我错过了什么吗?

添加简码时,您不想调用"date_counter"。 你的javascript正在寻找一个ID为"demo"的元素,所以你需要一个单独的简码函数,把它放在页面上。 试试这个。

function datecountershortcode_func( $atts ) {
return '<div id="demo"></div>';
}
add_action( 'init', 'register_shortcodes');
function register_shortcodes(){
add_shortcode('datecountershortcode', 'datecountershortcode_func');
}

最新更新