Pepe
Pepe

Reputation: 1002

Wordpress random post loop only for some posts of an category

Is there a simple way to say "integrate post 1 till 10 from category MyCat in a random loop"? I ask, because I dont want that the random loop integrate all my posts of a category. Thats the problem with this script:

<?php query_posts(array(
  'showposts' => 1,
  'orderby' => 'rand',
  'category_name' => 'MyCat'
));
if (have_posts()) : while (have_posts()) : the_post(); ?>

What I need is something like this:

<?php query_posts(array(
  'showposts' => 1,
  'orderby' => 'rand',
  'category_name' => 'MyCat'
  'post_number_of_category' => '1-10'    <-- something like this
));
if (have_posts()) : while (have_posts()) : the_post(); ?>

Can anybody help me?

Upvotes: 0

Views: 586

Answers (3)

shennan
shennan

Reputation: 11666

Have you tried using get_posts and the posts_per_page/numberposts option?

<?php

$rand_posts = get_posts(array(
  'numberposts' => 10,
  'posts_per_page' => 10,
  'orderby' => 'rand',
  'category_name' => 'MyCat'
));

foreach ( $rand_posts as $post ) {
  setup_postdata( $post );
  the_post();
}; ?>

According to WordPress, query_posts is inefficient, and showposts may be deprecated

Upvotes: 1

random_user_name
random_user_name

Reputation: 26170

What you may be looking for is the post__in option:

query_posts(array(
    'showposts' => 1,
    'orderby' => 'rand',
    'category_name' => 'MyCat',
    'post__in' => array(1, 2, 3, ...)
));

This allows you to define the specific post ID's that will be included in the query.

Note that this seems illogical to combine with category_name however, since you can specify the exact post ID's.

Upvotes: 0

Roy
Roy

Reputation: 4464

First hit on Google: https://wordpress.org/support/topic/how-to-get-random-post

<?php query_posts('orderby=rand&showposts=1&cat=75,76,77'); ?>

Upvotes: 0

Related Questions