Reputation: 737
I'm trying to combine 2 custom post types: 1) CPT = event 2) CPT = location, in the same foreach loop.
e.g.
<?php
$events = get_posts( array( post_type => event));
$locations = get_posts( array( post_type => location));
foreach($events as $event ) {
foreach($locations as $location ) {
echo $event->post_title;
echo $location->post_title;
}
}
?>
This however will only duplicate each post title. I also tried the following but it didn't work.
<?php
foreach($events as $index => $event ) {
$event->post_title;
$event->post_title[$index];
}
Upvotes: 0
Views: 1695
Reputation: 1278
I guess I found what you need:
$args = array(
'post_type' => 'event'
);
/* Get events */
$events = get_posts( $args );
foreach($events as $event ) {
echo '<article><h2>';
$event->post_title;
echo '<span>';
/*get location of event*/
$args2 = array(
'post_type' => 'location',
'meta_key' => '_location_ID',
'meta_value' => get_post_meta($event->ID,'_location_ID')
);
$locations = get_posts( $args2 );
foreach($locations as $location ) {
echo $location->post_title;
}
echo '</span></h2></article>';
}
Upvotes: 0
Reputation: 19888
First thing you should do is switch to using WP_Query instead of get_posts and you can do the following quick dirty example:
// The Query args
$args = array(
'post_type' => array( 'event', 'location' )
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while( $the_query->have_posts() ){
$post = $the_query->the_post();
echo '<li>' . get_the_title() . '<li>';
}
echo '</ul>';
}
Upvotes: 1
Reputation: 1278
I'm not sure what you want as an output. This should give you a list of all titles:
foreach($events as $event ) {
$titles[]=$event->post_title;
}
foreach($locations as $location ) {
$titles[]=$location->post_title;
}
echo '<ul>';
foreach($titles as $title ) {
echo '<li>'.$title.'</li>';
}
echo '</ul>';
Upvotes: 1