• Hi,

    I just found Michael H’s very nice solution to get a single post form each category on your page.

    <?php // cycle through categories, print 1 post for each category
    $categories=get_categories('orderby=name&order=ASC');
      foreach($categories as $category) {
          $posts=get_posts('showposts=1&cat='. $category->term_id);
          if ($posts) {
            echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
            foreach($posts as $post) {
              setup_postdata($post); ?>
              <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
              <?php
            } // foreach($posts
          } // if ($posts
        } // foreach($categories
    ?>

    It’s working magic, but I just need it even more specific. I cannot figure out how to omit categories from this query. I don’t want to show the ‘uncatagorised’ category for instance.

    To make it even more complicated I would like to omit the category that has most recently been posted in as well. Anyone any ideas?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Michael

    (@alchymyth)

    get_categories() has a exclude parameter

    https://codex.www.ads-software.com/Function_Reference/get_categories

    I would like to omit the category that has most recently been posted in

    might be possibly with an extra get_posts() snippet;

    replace:

    $categories=get_categories('orderby=name&order=ASC');

    with:

    $exclude = '1'; //exclude 'uncategorized'//
    $last = get_posts('numberposts=1'); //get the last post
    $last_cats = get_the_category($last[0]->ID); //get the category(ies) from the last post and add to the exclude list//
    foreach($last_cats as $last_cat) {
    $exclude .= ','.$last_cat->term_id;
    }
    $categories=get_categories('orderby=name&order=ASC&exclude='.$exclude);

    (one post per category with some excludes)
    full code: https://pastebin.com/ZpRYiuLA

    (not much tested)

    Thread Starter jordas

    (@jordas)

    You are my hero alchymyth,

    works like a charm!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘showing single posts from categories revisited’ is closed to new replies.