I have a hard time figuring out what's wrong with this code.
What I'm trying to do: setup up a custom field in admin using the ACF plugin to lists in a meta-box on all pages a list of testimonials (custom-post-type). From the drop-down menu the client can select a testimonial that will show up on that specific page.
I'm using a slightly modified version of twentytwelve theme and this is the code I'm using in my front_page template.
The code:
<?php $featured_testimonial = get_field('testimonial', $post_object->ID); ?>
<?php foreach ($featured_testimonial as $post_object): ?>
<a href="<?php echo get_permalink($post_object->ID); ?>">
<p class="descr"><?php echo get_the_title($post_object->ID) ?></p>
</a>
<?php endforeach; ?>
The problem: this code doesn't show anything on the front-page. I did a print_r( $post_object )
and it showed all the info in my testimonial (title, date, content etc).
The solution: For the last 2/3 days I'm trying to get an answer on the ACF support forums and this is the reply I got:
The post object field will return a post object, not HTML. using the_field on a post_object field will result in nothing being displayed.
You need to store it as a variable, then use the ID or post_title variable to output the desired HTML
Did I not understand the solution or I'm actually doing exactly what the message says and the problem is elsewhere?
Later edit: This is my current setup in ACF for the testimonial field:
Rules: Post Types - Page. Field Name - Testimonial. Field Type: Post Object. Post type: Testimonial. Filter from taxonomy: All.
The 'rules' means that the custom field will only appear on pages, and it will only list 'post objects' from the 'testimonial' custom post type. In admin everything seems to be working fine, it's just that I can't get anything to show up on the front-end.
Final edit: Following the suggestion of @s1lv3r I changed the field-type from 'post-object' to 'relationship'. I've also modified the code like this:
<?php $posts = get_field('testimonial'); ?>
<?php if( $posts ): ?>
<?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>
<?php setup_postdata($post); ?>
<?php echo get_the_excerpt(); ?>... <a href="<?php the_permalink(); ?>">+More</a>
<?php the_title(); ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
Now everything works OK on the front-end. Thanks everyone for helping.