setup_postdata is not returning any values

I am using ACF to create a custom field called facilities. Within that field is a repeater field called facility. So each store has ‘facilities’, which contains a number of ‘facility’.

What I am doing is looping through each of my stores, getting the ‘facilities’, looping through each ‘facility’ within that, and displaying it.

Here is a reference to the code I am using.

My code:

if( get_field( 'facilities' ) ):

    //print_r( get_field('facilities')  );
    $post_objects1 = get_field('facilities');

    if( $post_objects1 ):

        foreach( $post_objects1 as $post ): // variable must be called $post (IMPORTANT)
            setup_postdata($post); 
            print_r($post);
            ?>
            <h1><a href="https://wordpress.stackexchange.com/questions/214731/<?php the_permalink(); ?>">Title is <?php echo the_title(); ?></a></h1>
            <?
        endforeach; 
        wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly 

    endif;

endif;

Unfortunately the template tags are not working, they are just blank.

I had a look on the WordPress codex on the setup_postdata page and it says use global $post;, so I’ve done that, but still no luck.

I’ve tried print_r $post and I get the following:

Array ( [facility] => WP_Post Object ( [ID] => 1244 [post_author] => 2 [post_date] => 2015-12-28 14:48:55 [post_date_gmt] => 2015-12-28 14:48:55 [post_content] => [post_title] => Parking [post_excerpt] => [post_status] => publish [comment_status] => closed [ping_status] => closed [post_password] => [post_name] => parking [to_ping] => [pinged] => [post_modified] => 2015-12-28 14:48:55 [post_modified_gmt] => 2015-12-28 14:48:55 [post_content_filtered] => [post_parent] => 0 [guid] => http://xxx/~xxx/xxx/?post_type=facility&p=1244 [menu_order] => 0 [post_type] => facility [post_mime_type] => [comment_count] => 0 [filter] => raw ) )

So $post does contain the correct data.

However, why is the_title();, etc, not working?

1 Answer
1

In order for the template tags to work the global $post variable needs to be set properly, your $post is probably local to the loop or file.

Put somewhere before the loop global $post

But realy, just don’t do it, all the functions you use there can accept a post object or post id as parameter and there is no need to use globals. something like

foreach( $post_objects1 as $p): 
 ?>
 <h1><a href="https://wordpress.stackexchange.com/questions/214731/<?php echo get_permalink($p->ID); ?>">Title is <?php echo get_the_title($p->ID); ?></a></h1>
 <?
endforeach;

Leave a Comment