第一do not use query_posts()
for secondary loops. 这个query_posts()
函数仅用于修改主循环查询。使用WP_Query()
或get_posts()
用于辅助循环查询。
而且showposts
已弃用。使用posts_per_page
相反
让我们使用WP_Query()
, 因为它与您当前的实现最为相似:
<?php
// First, let\'s eliminate some DRY,
// by making an array of our categories
$random_posts_cat_array = array( \'people\', \'development\', \'offsite\', \'contact\' );
// Globalize $post,
// since we\'re outside the primary loop
global $post;
$post_cats = get_the_category( $post->ID );
// First array object
$post_cat = $post_cats[0];
// Current post category ID
$post_cat_id = $post_cat->term_id;
// Current post category slug
$post_cat_slug = $post_cat->slug;
// Now, let\'s find out if we\'re displaying
// the category index for one of our categories
if ( in_array( $post_cat_slug, $random_posts_cat_array ) ) {
// Set up custom loop args
$random_posts_query_args = array(
// Only 3 posts
\'posts_per_page\' => 3,
// Ordered randomly
\'orderby\' => \'rand\',
// Exclude current post
\'post__not_in\' => array( $post->ID )
);
// Add Cat ID to custom loop args
foreach ( $random_posts_cat_array as $random_post_cat ) {
if ( $post_cat_slug == $random_post_cat ) {
// Add Cat ID
$random_posts_query_args[\'cat\'] = $post_cat_id;
}
}
// Run random posts query
$random_posts_query = new WP_Query( $random_posts_query_args );
// Setup random posts query loop
if ( $random_posts_query->have_posts() ) : while ( $random_posts_query->have_posts() ) : $random_posts_query->the_post();
// Loop output goes here
endwhile; endif;
// Be kind; rewind
wp_reset_postdata();
} else {
// Alternate output goes here, if any
}