dougan6402 2015-06-25 20:12
浏览 61
已采纳

使用php,我应该如何从数组中获取即将到来的日期并将其传递给javascript?

I have setup a loop for WordPress which gets the date from a custom field (date picker) and passes it to a array. I need to determine the closest date in the future (upcoming date) from that array.

<?php
  $today = current_time('m/d/Y');
  $args=array( 
    'meta_key' => 'opening', 
    'orderby' => 'meta_value', 
    'order' => 'ASC', 
    'posts_per_page' => -1, 
    'post_type' => 'event',
  ); 
  $query = new WP_Query($args); 
?>

<?php if($query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>

<?php 
  $date = DateTime::createFromFormat('Ymd', get_field('opening')); 
  $dates[] = $date->format('m/d/Y');
  endwhile; endif; wp_reset_postdata();
  print_r($dates);
?>

And pass it to javascript.

$('#tl').timeline({
  startItem  : '$resultOfUpcomingDateEvaluation',
});

Please advice, thanks for the time.

  • 写回答

1条回答 默认 最新

  • douao8353 2015-06-29 00:26
    关注

    Found a solution, little dirty so will be nice if someone has a more elegant one.

    I wrote a second loop with a similar setup, limiting the posts to 1 and comparing the meta_value with a var that gets current_time. Then i echo the result wrapping it in a div with a class that hides it (not elegant).

      <?php
        $today = current_time('Ymd');
        $args=array(
          'meta_key' => 'opening', 
          'orderby' => 'meta_value',
          'order' => 'ASC', 
          'posts_per_page' => 1, 
          'post_type' => 'event',      
          'meta_query' => array(
            'key' => 'opening',
            'compare' => '>=',
            'value' => $today,
          )
        ); 
      $query = new WP_Query($args); ?>
    
      <?php if($query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
    
      <?php 
        $date = DateTime::createFromFormat('Ymd', get_field('opening')); 
        $upcoming = $date->format('d/m/Y');
    
        endwhile; endif; wp_reset_postdata();
    
        echo '<div class="hide" id="upcomingdiv">';
        echo $upcoming;
        echo '</div>';
      ?>
    

    After that, on my javascript file, i get the element by ID and get the .textContent of the div that contains the result of the loop and store it to a variable.

    var setupUpcoming = document.getElementById("upcomingRef");
    var upcoming = setupUpcoming.textContent;
    

    Finally i pass the variable to the startItem.

    $('#tl').timeline({  
      startItem  : upcoming,
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录