0
votes

I’m having a little problem understanding what (my) PHP is doing when I’m trying to display different Custom Posts and Advanced Custom fields on the same page.

I have added different Advanced Custom Fields to a page, and I have custom posts that I am trying to display using the template.

I’m calling my custom fields throughout the template using:

<?php the_field(‘field-name’) ?>

My custom posts are called through loops like this (somewhere around the middle of the template):

<?php
  $args = array(
  'post_type' => ‘foo’
);

$foo = new WP_Query( $args );
if( $foo->have_posts() ) {

while( $foo->have_posts() ) {
  $foo->the_post();
?>
  <?php the_content() ?>                    
<?php
  }
}
else {
  // SOME MESSAGE
}
?>

The content of the Advanced Custom Fields is showing fine, above those loops. Below the loops it just doesn’t display.

I can’t figure out why the content is not showing up.

I assume it has to do with the while or if statements of the loops. If I remove the loops, the content of any Advanced Custom Field below does display.

1

1 Answers

2
votes

When you use WP_Query(), you are changing the default $post variable on the page each time you loop through a post. You need to call wp_reset_postdata() after your loop to reset that $post variable so it corresponds to the current page again. You can call the function after your 'while' loop -

<?php
$args = array(
    'post_type' => ‘foo’
);
$foo = new WP_Query( $args );

if( $foo->have_posts() ) {

    while( $foo->have_posts() ) { $foo->the_post();

        the_content();                    

    } wp_reset_postdata();
}
else {
  // SOME MESSAGE
}
?>