I’m working on a wordpress theme and I’ve added a custom WP_query loop. The loop itself works fine with no errors.
I’m also using some advanced custom fields, but for reasons I cannot fathom, when I try to print a custom field before the custom query loop, nothing is returned to the page but if I print the custom field after the loop, it appears just fine.
The following works (‘test’ returns its value to the page if I call it after the loop):
<div class="section blog-summaries">
<?php $the_blog_posts = new WP_Query( 'showposts=5' ); ?>
<?php while ($the_blog_posts -> have_posts()) : $the_blog_posts -> the_post(); ?>
<h5>» <a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h5>
<p><span class="the_date"><?php the_time('F j, Y'); ?></span>
<?php echo substr(strip_tags($post->post_content), 0, 200);?>...</p>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
<h3 class="title1"><?php the_field("test"); ?><span class="title-end"></span></h3>
</div>
… whereas if I try and print the value of the custom field ‘test’ before the custom loop, no value is returned to the page:
<div class="section blog-summaries">
<h3 class="title1"><?php the_field("test"); ?><span class="title-end"></span></h3>
<?php $the_blog_posts = new WP_Query( 'showposts=5' ); ?>
<?php while ($the_blog_posts -> have_posts()) : $the_blog_posts -> the_post(); ?>
<h5>» <a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h5>
<p><span class="the_date"><?php the_time('F j, Y'); ?></span>
<?php echo substr(strip_tags($post->post_content), 0, 200);?>...</p>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</div>
I’ve got several other custom fields after the loop, all appearing on the page properly.
Strangely, I’ve found that if I call the acf custom field ‘test’ much earlier in the file, it does render on the page… does this sound like a php nesting/syntax error..?
I can post the whole code if it helps.
Thanks in advance
When you call
the_field()
it uses theglobal $post
if no post ID is provided as the second argument. In your example, your call toWP_Query()
sets up “the loop” so ifthe_field()
is called before it ACF doesn’t know what post ID to return the value for so it (likely) uses the ID of the page you are viewing which probably doesn’t have that meta value set. You either need to pass in the ID of the post you would like to display the value for, or use it inside the loop.