• I’m working on a bit of code but am completely stuck on how to do this properly. I’m using the Advanced Custom Fields plugin to create relationships between my custom post types. The main post type is Clients, then I’ve associated each particular client to my certain other posts in other post types. What I want to achieve is each client to display with a list of the associated other posts. Here is what I have so far.

    <?php
       $loop = new WP_Query( array( 'post_type' => 'clients', 'posts_per_page' => 10 ) );
       $ids = get_field('attach_to_client', false, false);
    
       $query = new WP_Query(array(
    	'post_type'      	=> array('research', 'project_brief','persona','task_models', 'user_stories', 'style_guide'),
    	'posts_per_page'	=> -1,
    	'post__in'		=> $ids,
    	'post_status'		=> 'any',
        'orderby'        	=> 'modified',
    ));
     ?>
    <?php if($loop->have_posts()) : ?>
    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <div>
    <h3><?php the_title(); ?></h3>
    <?php if ($query->have_posts()) : ?>
    <ul>
    <?php
    	while($query->have_posts()) :
    		$query->the_post();
    ?>
    	<li><?php the_title(); ?></li>
    
    <?php endwhile; ?>
    </ul>
    <?php else: ?>
    
          <p>Oops, there are no posts.</p>
    
    <?php endif; ?>
    </div>
    <?php endwhile; endif; wp_reset_query(); ?>

    This gives me every client but also all the posts too. It doesn’t take into consideration whether or not it’s actually been associated. How do I get it to only show the clients that have something posted in association with the client then hide the rest.

Viewing 2 replies - 1 through 2 (of 2 total)
  • An easier way to do this would be to use Custom Taxonomies (either categories or tags) for your Custom Post Type, then choose the Category or associate a Tag that is your Client Name.

    You don’t need ACF for this particular function, all you would do then is query for Posts related by Tags, or even easier just modify the tags.php (or category.php) template file (if your Theme has one, or create one if it doesn’t) as the standard WP query for those template will do what you want.

    Post back if you need more direction on setting up Custom Taxonomies – I do this on Custom Post Types and it works great. I do also use ACF, but not for creating relationships, just for customizing the content entry/edit screen.

    Thread Starter Chris Da Sie

    (@cjdsie)

    Perfect. That actually made a huge difference. Also it will be way easier to manage in the future too. Thanks.

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Getting only associated posts’ is closed to new replies.