• Resolved marissawells

    (@marissawells)


    I have a category called “Blogs.” Within that category, there are several subcategories. I would like to be able to pull only one post per subcategory without specifying the subcategories manually – mainly because more subcategories are going to be added as time goes on.

    So does anyone know how I could achieve this? I know how to use multiple loops if I know and specify what the subcategory is, but not in a case like this where I just want to automatically find any category that’s a child of the blogs category…

    Any help would be greatly appreciated!

Viewing 4 replies - 1 through 4 (of 4 total)
  • MichaelH

    (@michaelh)

    Could use get_categories with the child_of= to get all the child categories then use that to retrieve one post for each category.

    I didn’t test this but something like:

    <?php
    // in category template, get child categories of queried category and if there are child cats, get one post for each child
    if ( is_category() ) {
    $categories = get_categories('child_of='.get_query_var('cat'));
    if ( $categories ) {
      foreach($categories as $category) {
          $posts=get_posts('showposts=1&amp;cat='. $category->term_id);
          if ($posts) {
            echo 'Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>
     ';
            foreach($posts as $post) {
              setup_postdata($post); ?>
              <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
    
              <?php
            } // foreach($posts
          } // if ($posts
        } // foreach($categories
      } // if (categories
    } // if (is_category
    ?>

    forums still messing up entities so change &amp; to &

    code works brilliantly! Is there a way to show posts if there are no subcategories?

    Thread Starter marissawells

    (@marissawells)

    Works great! Thanks so much!

    Do posts show on category page for you if there are no subcategories? I get a blank page when there aren’t subcategories.

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Show one post per subcategory’ is closed to new replies.