WordPress.org

Ready to get started?Download WordPress

Forums

Get posts from a random child category (5 posts)

  1. Aznbai
    Member
    Posted 1 year ago #

    Hello everyone! =)

    I´m trying to create a loop that would return
    posts from a random subcategory that belongs to a given category(ID=3).

    • I´ve tried to express it like
      query_posts('&cat=rand,-1,-2-3' );
      in order to except all "wrong" categories and randomize the rest.
    • I´ve also tried to adoptthis code
      <?php
      /**
       * PickRandomCategory()
       * Returns X category ids.
       * @param int $amount
       * @return array $return
       */
      function PickRandomCategory($amount){
      if (!is_int($amount))
          return false;
      
      mt_srand((double)microtime()*1000000);
      $ids = array();
      $return = array();
          $cats = get_categories(array('hide_empty' => 1));
              foreach ($cats as $cat)
                  $ids[] = $cat->cat_ID;
      
              shuffle($ids);
      
                  for ($j = 0; $j < $amount; $j++){
                      $return[] = $ids[$j];
                  }
          return $return;
      }
      
      // $random_cat will now have 3 array elements - filled with id's.
      $random_cat = PickRandomCategory(3);
      
      ?>

      but it seems that this function does not works properly..

    Please help! =)

    Bless!
    Thank you!

  2. Pioneer Valley Web Design
    Member
    Posted 1 year ago #

    Quite an extensive primary post...please review the Codex.

  3. Aznbai
    Member
    Posted 1 year ago #

    Could somebody give me a hint about some WP function that could handle such query?

    I would be happy to hear any ideas about implementation of a subcategory randomisation.

  4. keesiemeijer
    moderator
    Posted 1 year ago #

    Try it with a loop like this:

    <?php   // get all child categories from category 3
    	$categories = get_categories('child_of=3&hide_empty=1');
    	if(!empty($categories)) :
    
    		// get random child category object
    		$random_category = $categories[rand(0, (count($categories)-1))];
    
    		// The Query
    		$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    		$the_query = new WP_Query('cat=' . $random_category->term_id . '&posts_per_page=10&paged=' . $paged );
    ?>
    
    <?php  while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    
    			<h2><?php the_title(); ?></h2>
    			<?php the_content(); ?>
    
    		<?php endwhile; ?>
    
    	<?php wp_reset_postdata(); ?>
    <?php endif; ?>
  5. Aznbai
    Member
    Posted 1 year ago #

    i have changed $categories = get_categories('child_of=3&hide_empty=1');
    to
    $categories = get_categories('parent=3&hide_empty=1');

    and it seems to work!
    many thanks!

Topic Closed

This topic has been closed to new replies.

About this Topic