在单个foreach循环中组合2个自定义帖子类型


Combine 2 custom post types in a single foreach loop

我试图结合2个自定义帖子类型:1)CPT =事件2)CPT =位置,在同一个foreach循环。

<?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];
  }

我不确定您想要什么作为输出。这会给你一个所有标题的列表:

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>';

您应该做的第一件事是切换到使用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>';
}

我想我找到你需要的了:

$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>';
}