Home › Forums › General Issues › Get ALL fields for ALL posts in one array › Reply To: Get ALL fields for ALL posts in one array
In that case, you’ll want to use the WP Post Object. You can then add the ACF fields array to each post. I’ve tried to make the comments as verbose as possible. I hope this helps!
<?php
// Get arguments for all posts
$args = array(
'posts_per_page' => -1,
);
// Create the array for all posts AND all ACF fields
$all_posts = array();
$all_acf_fields = array();
// Set up the query
$the_query = new WP_Query( $args );
// Setup the loop
if ( $the_query->have_posts() ):
while ( $the_query->have_posts() ): $the_query->the_post();
// Get WP Post Object
$fields = get_post();
// Get ACF fields
$acf_fields = get_fields();
// Push each $fields object into the $all_posts array
array_push($all_posts, $fields);
// Push each ACF array into the $all_acf_fields array
array_push($all_acf_fields, $acf_fields);
endwhile;
// Restore original Post Data
wp_reset_postdata();
// Arbitrary array counter
$i = 0;
/*
* The magic
* For every post in the array of $all_posts,
* add a new object key of "acf_fields" to the post object.
*
* This contains the array of ACF fields for that post.
*
* Lastly, increment the array for each post.
*/
foreach ($all_posts as $p):
$p->acf_fields = $all_acf_fields[$i];
array_push($all_posts, $p);
$i++;
endforeach;
// Print the result here and do what you choose
echo '<pre>';
print_r($all_posts);
echo '</pre>';
endif;
?>
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.