1

I've set up two different custom post types – one for categories and one for posts. I've attached the posts to the categories with the CMB2 plugin. I now want to display all the attached/related posts on each category page. I'm able to display the different ID's from the array, but not the post content.

Trying to get attached posts:

$attached_users = get_post_meta( get_the_ID(), 'pr2_cmb2_attached_posts', true );

foreach ( $attached_users as $user ) {
    $employee = get_post( $user );
}

Trying to display the content from the attached posts

<?php while ( have_posts() ) : the_post(); ?>
    <?php echo get_the_title($employee);?>
    <?php echo get_the_post_thumbnail($employee);?>
<?php endwhile; // end of the loop. ?>

1 Answers1

0

The plugin you are using gives you an array of ids. Using this ids gives you the possibility to get the post object by using get_post($id).

The function gives you a post object: https://developer.wordpress.org/reference/functions/get_post/

But if you just want to use functions like get_the_title() you only need the post id, not the whole post object.

Well, you already got all the data you need and do not need to get the post object. The plugins gives you an array of post ids.

// get array of post ids
$attached_users = get_post_meta( get_the_ID(), 'pr2_cmb2_attached_posts', true );

// loop through posts using post ids
foreach ( $attached_users as $user ) {
    echo get_the_title( $user );
    echo get_the_post_thumbnail( $user, 'thumbnail' );
}
rank
  • 2,361
  • 2
  • 10
  • 20