我尝试合并两种自定义帖子类型:1)CPT =事件2)CPT =位置,在同一个foreach循环中。
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;
}
}
?>
然而,这只会复制每个帖子标题。我也尝试过以下但是它没有用。
<?php
foreach($events as $index => $event ) {
$event->post_title;
$event->post_title[$index];
}
答案 0 :(得分:1)
我不确定你想要什么作为输出。这应该给你一个所有标题的列表:
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>';
答案 1 :(得分:1)
你应该做的第一件事是切换到使用WP_Query而不是get_posts,你可以做以下快速脏的例子:
// 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>';
}
答案 2 :(得分:0)
我想我找到了你需要的东西:
$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>';
}