Never ever use query_posts
, it creates an endless amount of issues as it breaks the main query object on which so many build in functions, custom functions and plugin rely on. It is pure evil and you should avoid it as such as well.
For custom queries, use WP_Query
or get_posts
, if you simply need to alter the current main query (except on single pages, static front pages and true pages), use pre_get_posts
.
Your query is completely wrong and you are not doing anything with your random category number. Lets look at your code, rewritten; (NOTE: Requires PHP 5.4+)
$numbers = ['5','6','7']; //id's of the categories
// Get a random key from the array
$rand_key = array_rand( $numbers );
// Get a random category ID from the array
$random_cat_ID = $numbers[$rand_key];
// Now build our query args
$args = [
'cat' => $random_cat_ID,
'posts_per_page' => 1
];
$q = new WP_Query( $args );
// Run the loop
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
// Display what you need from the loop like title, content etc
}
wp_reset_postdata();
}
EDIT
If you need to shuffle the array of category ID’s in $numbers
and then get the latest post from each category, we need a different approach here. You need to realize that you will need to run a query for each category. There is really not much you can do about this because you will be using random ordering.
Lets look at the code:
$numbers = ['5','6','7']; //id's of the categories
// Shuffle the array
$rand_key = shuffle( $numbers );
// Run a foreach loop to get the newest post from the categories
foreach ( $numbers as $cat_id ) {
$args = [
'posts_per_page' => 1,
'cat' => $cat_id,
'no_found_rows' => true // Legally skips pagination
// Add any extra arguments
];
$q = new WP_Query( $args );
// Run the loop
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
// Display what you need from the loop like title, content etc
}
wp_reset_postdata();
}
}