Search code examples
wordpressadvanced-custom-fields

WP_Query in wordpress and include ACF in results


I try to fetch all posts from a custom post type in Wordpress and include the advanced custom fields (ACF) in the results as well, in order to generate a JSON file with the data.

$query = new WP_Query(array(
  'post_type' => 'resources',
  'post_status' => 'publish',
  'posts_per_page' => -1,
));

echo "var json=". json_encode($query->get_posts());

With a simple WP_Query, ACF data are not included and I have to iterate in the results and fetch all ACF manually one by one. Is there any way to include them in the original WP_Query results?


Solution

  • This would be my way of doing it.

    Push whatever you want to the array and encode it.

    <?php
    $array = array();
    
    $args         = array(
        'post_type'      => 'resources',
        'post_status'    => array( 'publish' ),
        'nopaging'       => true,
        'posts_per_page' => '-1',
        'order'          => 'ASC',
        'orderby'        => 'ID',
    
    );
    $queryResults = new WP_Query( $args );
    
    if ( $queryResults->have_posts() ) {
        $counter = 0;
        while ( $queryResults->have_posts() ) {
            $queryResults->the_post();
            $array[ $counter ][ 'ID' ]           = get_the_ID();
            $array[ $counter ][ 'name' ]         = get_the_title();
            $array[ $counter ][ 'thumbnailURL' ] = get_the_post_thumbnail_url();
            $array[ $counter ][ 'place' ]        = get_field( 'resource_location' );
            //etc etc etc
    
            $counter++;
        }
    
        $jasoned = json_encode( $array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
        echo $jasoned;
    } else {
        //nothing found
    }
    wp_reset_postdata();