• I found a solution that will post my category title+posts randomly and by the number i set, my the problem is i cant list it by twos with the category title because they act like separate set of queries, i cant put the two result in one

      coz the second post result creates that another
      like a separate query the title only comes with the first post, so i cant combine the cat title and the two posts from the query. Is there a css fix for this to make it like?

      <h1>title1</h1> | <h1>title2</h1> | <h1>title3</h1>
      <>post1</> | <>post3</> | <>post5</>
      <>post2</> | <>post4</> | <>post6</>
      Functions*

      function get_posts_for_cat_ordered( $cats = array(), $posts_per_cat = 2 ) {
        if ( empty($cats) ) return false;
        $args = array('posts_per_page' => 99, 'category__in' => $cats, 'orderby' => 'rand');
        $q = new WP_Query( $args );
        $posts_ordered = array();
        $done = 0;
        while ( $q->have_posts() ) : $q->the_post();
          global $post;
          $cats = get_the_category();
          $cat = array_shift( $cats );
          if ( ! isset($posts_ordered[$cat->slug]) )
            $posts_ordered[$cat->slug] = array('term' => $cat);
          if ( ! isset($posts_ordered[$cat->slug]['posts']) )
            $posts_ordered[$cat->slug]['posts'] = array();
          if ( count($posts_ordered[$cat->slug]['posts']) == $posts_per_cat ) {
             $done++;
             if ( $done == count($cats) ) return $posts_ordered;
             continue;
          }
          $posts_ordered[$cat->slug]['posts'][] = $post;
        endwhile;
        wp_reset_postdata();
        return $posts_ordered;
      }
      $cats = array(12, 13, 14);
      $posts_per_category = 2;
      $posts_ordered = get_posts_for_cat_ordered( $cats, $posts_per_category );
      
      if ( ! empty($posts_ordered) ) { foreach ( $posts_ordered as $loop_data) {
      
        // Example category heading
        echo '<h2><a href="' . get_term_link($loop_data['term'], 'category') . '">' . $loop_data['term']->name . '</a></h2>';
        global $post;
        foreach ( $loop_data['posts'] as $post) {
          setup_postdata($post);
      ?>
      
        <!-- Example post content -->
        <?php the_title(); ?><br />
        <?php the_content(); ?><br />
      
      <?php
        }
        wp_reset_postdata();
      
      } }

      Also it doesnt work on posts with two categories or more..

  • The topic ‘Retrieve number of post from multiple categories.’ is closed to new replies.