Support

Account

Home Forums General Issues Relationship field on custom post types

Solved

Relationship field on custom post types

  • I’ve set up a custom post type for testimonials, on the testimonial page there is a relationship field (display_on_page) where you would select which page to display the testimonial on.

    The issue is that the testimonial displays on everypage, and seems to simply ignore the display_on_page field

    Does anyone know if I am doing something wrong on the below?

    Any help would be appreciated 🙂

    <?php 
    	$posts = get_field('display_on_page');
    	$args = array(
    	'post_type' => 'Testimonial',
    	'name'=> ($posts->post_name), 
    	);
    	$query = new WP_Query( $args );
    ?>		
    
    <?php if($query->have_posts()) : ?>
    	<?php while($query->have_posts()) : ?>
    	<?php $query->the_post(); ?>
    
    		<?php the_field('testimonial'); ?>
    		
    	<?php endwhile; ?>
    	<?php wp_reset_postdata(); ?>
    <?php endif; ?>
  • By default, the relationship field returns an array of post objects, so your $posts->post_name won’t return your desried post’s name. You’d have to dig into the array, or iterate through it. Or do something like set the relationship field to return an array of chosen post IDs instead, and pump THAT into your query using WP_Query’s ‘post__in’ parameter

  • Thanks a lot for the reply, I moved the ‘display_on_page’ field to the actual page and did this:

    <?php if( $related_pages = get_field( 'display_on_page' ) ): ?>
    	<?php foreach( $related_pages as $post ): ?>
    	<?php setup_postdata( $post ); ?>
    
    		<?php the_field('testimonial'); ?>
    			
    	<?php endforeach; ?>
    	<?php wp_reset_postdata(); ?> 
    <?php endif; ?>

    Which resolved the issue, hope it helps someone 🙂

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.