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,
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?