Support

Account

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

  • Okay, so I got it working by using different post_object names and by removing the wp_reset_postdata();

    <?php
    
    $your_posts = new WP_Query( $args );
    
    // Loop starts here
    if ( $your_posts->have_posts() ) : while ( $your_posts->have_posts() ) : $your_posts->the_post();
    
    	// First post from a CPT
    	if( get_field('custom_post') ) {
    
    		$post_object_cpt = get_field('custom_post');
    
    		if( $post_object_cpt ) {
    
    			$post_cpt = $post_object_cpt;
    			setup_postdata( $post_cpt ); 
    			?>	
    			<a href="<?php the_permalink($post_object_cpt->ID); ?>"><?php if(get_field('CPT_name', $post_object_cpt->ID)) { the_field('CPT_name', $post_object_cpt->ID); } ?></a>
    			<?php
    			
    		}
    		
    	}
    	
    	// Second post from a CPT
    	if( get_field('custom_post2') ) {
    
    		$post_object_cpt2 = get_field('custom_post2');
    
    		if( $post_object_cpt2 ) {
    
    			$post_cpt2 = $post_object_cpt2;
    			setup_postdata( $post_cpt2 ); 
    			?>	
    			<a href="<?php the_permalink($post_object_cpt2->ID); ?>"><?php if(get_field('CPT_name', $post_object_cpt2->ID)) { the_field('CPT_name', $post_object_cpt2->ID); } ?></a>
    			<?php
    			
    		}
    		
    	}
    	
    endwhile; else: ?><p>Sorry, there are no posts to display</p>
    <?php endif; ?>
    <?php wp_reset_query(); ?>

    Can anyone please tell me if this is the correct way of doing it?