您的两个查询是相同的,这意味着您只需要其中一个查询。基本解决方案是:
global $testimonials;
$testimonials = new WP_Query(array(
\'posts_per_page\' => 2, /* <-- get both */
\'post_type\' => \'testimonial\',
\'post_status\' => \'published\',
\'orderby\' => \'rand\',
\'ignore_sticky_posts\' => true /* you need this to control post count accurately */
));
// header
if ($testimonials->have_posts()) {
while($testimonials->have_posts()) {
$testimonials->the_post();
// whatever you need to do with the post content
break; // stop the Loop; no complex logic needed since you are printing one and moving on
}
}
// sidebar
// pretty much the same as the above
global $testimonials;
// this Loop will pick up where the other left off
if (!empty($testimonials) && $testimonials->have_posts()) {
while($testimonials->have_posts()) {
$testimonials->the_post();
// whatever you need to do with the post content
}
}
也许有更好的方法可以做到这一点。我会强烈考虑将整个事件合并到一个类中,并完全避免全局事件。
class Testimonial_Loop {
static $testimonials = false;
function get_testimonials() {
if (empty(static::$testimonials)) {
static::$testimonials = new WP_Query(array(
\'posts_per_page\' => 2, /* <-- get both */
\'post_type\' => \'testimonial\',
\'post_status\' => \'published\',
\'orderby\' => \'rand\',
\'ignore_sticky_posts\' => true
));
}
return static::$testimonials;
}
function loop() {
$testimonials = self::get_testimonials();
if ($testimonials->have_posts()) {
while($testimonials->have_posts()) {
$testimonials->the_post();
the_title();
// whatever you need to do with the post content
break; // stop the Loop; no complex logic needed since you are printing on and moving on
}
}
}
}
Testimonial_Loop::loop();
Testimonial_Loop::loop();
以及使用函数和静态变量的第三种解决方案:
function testimonial_loop() {
static $testimonials = false;
if (empty($testimonials)) {
$testimonials = new WP_Query(array(
\'posts_per_page\' => 2, /* <-- get both */
\'post_type\' => \'post\',
\'post_status\' => \'published\',
\'orderby\' => \'rand\',
\'ignore_sticky_posts\' => true
));
}
if ($testimonials->have_posts()) {
while($testimonials->have_posts()) {
$testimonials->the_post();
// whatever you need to do with the post content
break; // stop the Loop; no complex logic needed since you are printing on and moving on
}
}
}
testimonial_loop();
testimonial_loop();