Home › Forums › ACF PRO › Exclude Current Post in Foreach › Reply To: Exclude Current Post in Foreach
Before looking at the problem of excluding the current post, as it stands your nested loops cannot work.
The reason is that wp_reset_postdata()
always resets $post to the current post in the main WP query, it does not reset $post to a previous value. This is not stressed nearly strong enough in any WP documentation, not to mention that it’s not covered very well by people that have blogged about dealing with it.
You cannot use setup_postdata()
and wp_reset_postdata()
beyond a secondary query.
With nested post loops beyond the secondary you must access the post and get information about the post in a different way. For example:
if ($third_nesting_posts) {
foreach ($third_nesting_posts as $third_nesting_post) {
$title = get_the_title($third_nesting_post->ID);
$value = get_field('field_name', $third_nesting_post->ID);
}
}
Also, another issue is that you’re using the same variable for multiple calls in nested loops.
$posts = get_field('field_name');
foreach ($posts as $post) {
// this overwrites the value of the array you're looping over
$posts = get_field('field_name', $post->id);
}
The second time through the loop you’ll actually be looking at the second post from the second time you got the field value and not the second value of the original array.
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.