Reputation: 836
I have the code below. $related is array result of db query and contains data.
Queried data consist of posts belonging to different groups (post_type). I want to group the queried objects within their post_type. The code below works BUT... what I want is create different ULs for each post_type. As it is below, there will be a UL element foreach post found in the query. So UL should stay out of foreach, but on the other hand how can i get post_type out of foreach? I am a bit lost here :(
$related = p2p_type( 'accommmodation-to-places' )->get_connected( get_queried_object_id() );
foreach($related->posts as $post) {
echo '<ul class="related-'.$post->post_type.'">'; // this shouldn't be here
if($post->post_type == 'hotels') {
echo '<li><a href="'.get_permalink($post->ID).'" rel="permalink">'.get_the_post_thumbnail($post->id, '48').$post->post_title.'</a></li>';
}
echo '</ul>'; // this shouldn't be here
}
wp_reset_query();
Upvotes: 0
Views: 1308
Reputation: 522175
So first, group the posts by their type:
$groups = array();
foreach ($related->posts as $post) {
$groups[$post->post_type][] = $post;
}
Then loop through the groups and output the lists:
foreach ($groups as $type => $posts) {
printf('<ul class="%s">', htmlspecialchars($type));
foreach ($posts as $post) {
printf('<li>...</li>', ...);
}
echo '</ul>';
}
Upvotes: 3