我正在创建两个不同的WP\\u查询对象,分别用于我使用的两种不同的帖子类型。在创建输出时,我希望遍历其中一个对象,同时遍历另一个对象,这样我就可以将它们的各个部分一起输出。下面是我想完成的一个例子:
$rotator_args = array(
\'post_type\' => \'rotator\',
);
$rotator = new WP_Query($rotator_args);
$numrotators = $rotator->post_count;
$testimonial_args = array(
\'post_type\' => \'testimonial\',
\'posts_per_page\' => $numrotators,
);
$testimonial = new WP_Query($testimonial_args);
while ( $rotator->have_posts() ) :
$rotator->the_post(); //setup the rotator posts
$testimonial->the_post(); //this breaks things, understandably
$rotator_image = get_the_post_thumbnail($rotator->ID, \'large\');
$testimonial_image = get_the_post_thumbnail($testimonial->ID, \'large\');
$return .= \'<div>\' . $rotator_image . \'</div>\';
$return .= \'<div>\' . $testimonial_image . \'</div>\';
endwhile;
return $return;
然而,这是行不通的。取出
$testimonial->the_post();
(以及相关的
$testimonial
相关代码)修复问题。
SO网友:Jonathan Christopher
Edit: Bill\'s refactor 比我的胶带好多了Edit: 此外,我的编辑将坚持同样的推荐,这甚至不是期望的结果。再次:请参见Bill\'s refactor
你遇到的麻烦是$post。每次启动\\u post()$post时,都会有适用的数据。我建议如下:
global $post;
$rotator_args = array(
\'post_type\' => \'rotator\',
);
$rotator = new WP_Query($rotator_args);
$numrotators = $rotator->post_count;
$testimonial_args = array(
\'post_type\' => \'testimonial\',
\'posts_per_page\' => $numrotators,
);
$testimonial = new WP_Query($testimonial_args);
if( $testimonial->have_posts() )
{
$testimonial->the_post();
$my_testimonial = $post;
}
while ( $rotator->have_posts() ) :
$rotator->the_post(); //setup the rotator posts
$rotator_image = get_the_post_thumbnail($rotator->ID, \'large\');
$testimonial_image = get_the_post_thumbnail($my_testimonial->ID, \'large\');
$return .= \'<div>\' . $rotator_image . \'</div>\';
$return .= \'<div>\' . $testimonial_image . \'</div>\';
endwhile;
return $return;