Support

Account

Home Forums General Issues Converting ACF field values to JS Array

Solved

Converting ACF field values to JS Array

  • I am trying to enable only those dates in the Jquery datepicker , which were saved as acf date field values. First I have set this
    $date_field_array = get_field('event_the_date');

    then converting this to a js array
    var availableDates = <?php echo '["' . implode('", "', $date_fields_array) . '"]' ?>;

    But it is only giving this as result
    var availableDates = [""];

    Is this an issues ? Or due to wrong code ?

  • Not sure what you’re trying to accomplish with this.

    If “event_the_date” is a date field then it does not store and array, it holds a single value representing the date entered.

  • Thanks for your Reply John..
    I am trying to get all the values of “event_the_date” from all the available custom post type. Then converting this array of values to a js array

  • This $date_field_array = get_field('event_the_date'); only gets a single value from a single post.

    To get all values from all posts you first need to do a query to get all the posts, then you need to loop though all of those posts and get the field from each post.

    
    $args = array(/* your query args here */);
    $my_query = new WP_Query($args);
    if ($my_query->have_posts()) {
      $dates = array();
      while (($my_query->have_posts()) {
        $my_query->the_post();
        $dates[] = get_field('event_the_date');
      }
      // output dates to JS here
    }
    
  • I have tried this , but the JS array remains empty. Can you please give an example of converting this $dates[] to a JS array variable ?

  • This is my final code so far ! And its working .. Thanks John

    <script>  
        <?php 
           $ea_args = array(
            'post_type'        => 'event-main',
            'posts_per_page'   => -1,
           
               );
            $ea_query = new WP_Query( $ea_args ); 
    	    
            if ( $ea_query->have_posts() ) {
    		$dates_enable = array();
    			
             while ( $ea_query->have_posts() ) {
              $ea_query->the_post(); 
                   $dates_enable[] = get_field('event_the_date');
               }
    		$dates_js_array = json_encode($dates_enable);
            } // end if
    wp_reset_query();
        ?>  
        var enableDays = <?php echo $dates_js_array; ?>;
        console.log(enableDays);
    </script>
  • Sorry I didn’t get back to you above. Glad you got it working.

Viewing 7 posts - 1 through 7 (of 7 total)

The topic ‘Converting ACF field values to JS Array’ is closed to new replies.