Home › Forums › Add-ons › Repeater Field › Getting post object from repeater field
Hi I am attempting to get the post object from a repeater field but I can’t quite get it working.
The code I currently have displays the current page title instead of the post selected with the post object in my repeater field.
It displays the correct number of rows set in the repeater field just not the post object.
I am using $user_id = get_current_user_id(); since the repeater field is set to display when editing a users profile.
<ul> <!-- Start Repeater --> <?php $user_id = get_current_user_id(); if( have_rows('repeater', 'user_'.$user_id)): // check for repeater fields ?> <?php while ( have_rows('repeater', 'user_'.$user_id)) : the_row(); // loop through the repeater fields ?> <?php // set up post object $post_object = get_sub_field('sub-repeater-field', 'user_'.$user_id); if( $post_object ) : $post = $post_object; setup_postdata($post); ?> <li> <?php the_title(); ?></li> <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?> <?php endif; ?> <?php endwhile; ?> <!-- End Repeater --> <?php endif; ?> </ul>
Any assistance would be greatly appreciated.
get sub field doesn’t require giving the post id, change to this
but I’m not sure that will fix the problem. Make that change and see what happens.
If that does not fix it. is the post object field set to allow multiple selections or a single selection?
Thanks for the reply. Unfortunately that didn’t resolve it. THe post object field is set to allow a single selection.
Are you returning the post object or post id. Can you post a screenshot of the post object field settings?
Post object, here’s a link to the screenshot of options.
Everything looks like it should be working.
Is this being run in the code of a template or is it inside a function? The only thing that I can think of is that the global $post is not defined where this is run.
Try adding this before your loop
Awesome thanks that worked.
It was being run in a widget that allows PHP and then placed on a page.
I’m having a similar problem – my code outputs the current page title.
When I add
global $post; before my loop, it then just outputs the chronologically first post on my site.
The code is running within a template.
Any help would be greatly appreciated.
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!
🚨 The 2023 ACF Annual Survey closes tomorrow! This is your last chance to complete the survey and help guide the evolution of ACF. https://t.co/0cgr9ZFOJ5— Advanced Custom Fields (@wp_acf) May 18, 2023
© 2023 Advanced Custom Fields.