Support

Account

Home Forums General Issues Post_object inside loop Reply To: Post_object inside loop

  • So, here’s you problem.

    You have a main WP query, and this loops over the posts.

    Then you have your secondary query

    
    $your_posts = new WP_Query( $args );
    
    // Loop starts here
    if ( $your_posts->have_posts() )
    

    then you are referring to another post.

    Here’s the common misconception, that wp_reset_postdata(), or any of the reset functions. This will not reset the post data to whatever was in it previously. This call always resets the post to the post in the main WP query. I explained this in more detail here https://support.advancedcustomfields.com/forums/topic/nested-post-object-fields/#post-48227

    When you’re nested more than 2 deep you can no longer safely use any of the WP reset functions.

    Instead of this

    
    if( $post_object ) {
      $post = $post_object;	
      setup_postdata( $post );
      ?>	
        <a href="<?php the_permalink(); ?>"><?php if(get_field('CPT_name')) {
          the_field('CPT_name'); } ?></a>
        <?php
        wp_reset_postdata();
    }
    

    you need to do something like this

    
    if( $post_object ) {
      ?>	
        <a href="<?php 
          echo get_permalink($post_object->ID); ?>"><?php 
          if (get_field('CPT_name', $post_object->ID)) {
            the_field('CPT_name', $post_object->ID);
          } ?></a>
      <?php 
    }