I have two post types: person and company. There’s a Post Object custom field when adding a new person to where the user can select which company that person belongs to.
On the page that lists every person, I want to be able to retrieve that person’s company’s data (including
the_title and some custom fields) as well as data within that person’s post. I’ve tried referring to the documentation but I can’t seem to get everything working correctly.
I tried the first method with
wp_reset_postdata() and that retrieved the data for the company for that person successfully, but then the entire page’s query was reset and the rest of the fields for the person (and everything else) wouldn’t display, understandably.
I then tried the second method, using
foreach, but then that would just loop through every company for every person, which isn’t what I want. If I could use this method, but specifically target the company that was selected for that specific person, then that would work.
Maybe I’m missing something really obvious, but I would really appreciate some assistance with this.
Fantastic plugin, by the way!
I apologize I wasn’t very specific. The template I’m using is a custom page template.
Here’s the code for the first method listed in the documentation, setting the
post object and using
wp_reset_postdata(). The result is that only the person’s name (line 12) and the correct company name and link is displayed for that person. Everything else, including the person’s title and biography don’t show up.
The more I thought about it, the more I think the loop method listed in the documentation isn’t the method for what I’m trying to accomplish since I’m only trying to target one specific company from the post object.
Let me know if there’s any other information you need. Thanks again for your assistance!
The issue is 100% using
This function will reset the query back to the origional one set by WP, not the one on line 5! This is very important to understand.
You will need to not use the
wp_reset_postdata(). This is easy, just make use of the get functions like so:
<?php $post_object = get_field('person_company'); // Person's company Post Object field if( $post_object ): $company_name = get_the_title( $post_object->ID ); // Set company name from the person's company $company_link = get_field('company_link', $post_object->ID); // Set website url for the person's company ?> <p> <?php the_field('person_title'); // Custom field from the person post ?> <a href="<?php echo $company_link; ?>" target="_blank"><?php echo $company_name; ?></a> </p> <?php endif; ?>
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!
© 2019 Advanced Custom Fields. Subscribe