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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀