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

使用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.

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,
});