自定义POST类型的列倒计时

时间:2018-10-23 作者:abdelrhman kouta

我已经注册了自定义帖子类型,并为其创建了自定义列其中一列是倒计时,它的功能是从自定义的元日期和时间中减少NowTime,因此我通过javascript实现了它,这很好,但所有行只能获得一个值。这是我的代码:

这是注册列

 case \'reminder\':
        $reminder = remider_text();

        break;
这是javascript的函数

function remider_text(){
$date = get_post_meta($post_id, \'booking_date\', true);
$date_format = "M d, Y";
$meta = (!empty($date)) ? date($date_format, $date) : "";
$time = get_post_meta($post_id, \'time\', true);
$data = $meta ." ". $time;

if ($data == \'\') {
    echo \'N/A\';
    ?>
    <?php
    } else { ?>
                  <div id="countdown"></div>

<script>
    console.log(data)
// Set the date we\'re counting down to
var countDownDate = new Date(data).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 and 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);

    // Output the result in an element with id="demo"
    var elms = document.querySelectorAll("[id=\'countdown\']");
    for(var i = 0; i < elms.length; i++) 
    elms[i].innerHTML = days + "d " + hours + "h "
    + minutes + "m " + seconds + "s ";

    // Changing text color
    var elms_color = document.querySelectorAll("[id=\'countdown\']");
    for(var i = 0; i < elms_color.length; i++) 
    elms_color[i].style.color = days === 0 && hours < 3 ? \'red\' : \'\';

     // Changing text color
     var elms_color = document.querySelectorAll("[id=\'countdown\']");
    for(var i = 0; i < elms_color.length; i++) 
    elms_color[i].style.color = days === 2 && hours < 5 ? \'orange\' : \'\';

    // If the count down is over, write some text 
    if (distance < 0) {
        clearInterval(x);
        for(var i = 0; i < elms.length; i++) 
        elms[i].innerHTML = "Outdated";
    }
}, 1000);
</script>
      <?php }
?>
<?php}
以下是post meta日期和时间值

Aug 13, 2019 14:00
Oct 27, 2018 14:00
Oct 19, 2018 14:00
Oct 13, 2018 13:00
Oct 25, 2019 14:00
Oct 08, 2018 07:00
it just getting the last value for all rows

1 个回复
SO网友:Antti Koskinen

虽然您的问题看起来更像是一个通用的javascript问题,而不是特定于WordPress的问题,并且可能更适合其他论坛,如stackoverflow.com, 我想说你的代码中的问题是id="countdown" 对于所有倒计时元素。您应该使用class="countdown" 如果要在单个页面上多次使用该元素。您还可以通过执行console.log(elems);document.querySelectorAll.

结束