Home › Forums › Front-end Issues › Can't continue query after calling post object field
I’m using the following code to query the obituary custom post type. The visitation location is a post object field in ACF. I’m using the code from the documentation to call it, and it’s returning the correct location name, but after that I can’t reset the query. None of the following fields will populate. Please help!
<ul> <li><a href="<?php the_permalink(); ?>">Life Story and Service Details</a></li> <li>Visitation: <?php $date = get_field('visitation_date'); ?> <?php echo date("F j, Y", strtotime($date)); ?>, <?php the_field('visitation_time'); ?>, <?php $post_object = get_field('visitation_location'); if( $post_object ): // override $post $post = $post_object; setup_postdata( $post ); ?> <?php the_title(); ?> <?php wp_reset_postdata(); ?> <?php endif; ?> </li> <li>Service: <?php $date2 = get_field('service_date'); ?> <?php echo date("F j, Y", strtotime($date2)); ?>, <?php the_field('service_time'); ?> </li> <li>Burial: <?php the_field('burial_time'); ?></li> </ul>
Do you already have a secondary loop that is used for the query of the custom post type?
This is the query for the custom post type:
<?php $obit_query = new WP_Query( array( 'post_type' => 'obituary', 'posts_per_page' => 12 ) ); while ($obit_query->have_posts()) : $obit_query->the_post(); ?>
It works perfectly. If I remove the post object code all the fields display correctly.
The reason this is happening is that when you call
wp_reset_postdata(); the post data is being reset to the main post that would be displayed on the page and not the post associated with your secondary loop.
You’ll need to not use
$post = $post_object; setup_postdata($post);
and use an alternate method to get data for your post object, for example
$title = get_the_title($post_object->ID);
This worked! Thank you so much for your help!
You must be logged in to reply to this topic.
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’re hard at work on ACF 6.1, and Beta 1 is now available 🚀— Advanced Custom Fields (@wp_acf) March 16, 2023
This release includes custom post type and taxonomy registration, an improved experience when selecting field types, PHP 8.1 and 8.2 compatibility, and more!
Let’s take a look 🧵https://t.co/Y0WcAT11l4
© 2023 Advanced Custom Fields.