I have two custom post types: “unit” and “lesson”.
I want to assign each “lesson” to a “unit”.
I have successfully used a Post Object field to create a select list on the lesson edit page. My question is: how do I customize the loop to output which lessons are attached to each unit on the unit page?
Starting with a standard loop…
<?php
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
// Do something here...
}
echo '</ul>';
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
I’ve looked through the documentation and how-to section, but I can’t seem to figure this one out…
Thanks,
Andy
Hi @andymacleod
When on the unit
single page, you can load the lessons with a get_posts
function. You can learn more about this here:
http://www.advancedcustomfields.com/resources/how-to/how-to-query-posts-filtered-by-custom-field-values/
Notes:
1. You do not need to ‘modify’ the loop
2. Use get_posts to load the lessons and loop over them
3. Your meta_query args should find posts where 'post_object_field_name' => get_the_ID()
Thanks
E
I got it working! Here’s my code – just in case someone else finds it useful later on…
<?php // args
$args = array(
'numberposts' => -1,
'order' => 'ASC',
'orderby' => 'menu_order name',
'post_type' => 'lesson',
'meta_key' => 'attached_unit',
'meta_value' => get_the_ID()
);
// get results
$the_query = new WP_Query( $args );
// The Loop
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); ?>
Thanks so much for your help, Elliot! (ACF is simply superb!)
Andy