1

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="<?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?

0

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="<?php echo get_permalink($p->ID); ?>">Title is <?php echo get_the_title($p->ID); ?></a></h1>
 <?
endforeach;
  • Can you give an example please? – ravravrav Jan 16 '16 at 14:11
  • ok, it is a little different functions, but I added the example. – Mark Kaplun Jan 16 '16 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.