First, do not use query_posts()
for secondary loops. The query_posts()
function is intended only to modify the primary loop query. Use WP_Query()
or get_posts()
for secondary loop queries.
Also, showposts
is deprecated. Use posts_per_page
instead.
Let’s use WP_Query()
, as it will be the most analogous to your current implementation:
<?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
}