0

I have the following code that lists out the children categories on a separate page when you click on its parent category. The code renders a list like so:

Home › Archive for IQ Issue 7

  • Journal

  • news

  • world view

However I would like to retrieve the latest post from each of these categories and print underneath the category name. How could I achieve this within the loop below? I have tried several foreach loops but none seem to print the correct info. Thanks in advance.

category.php

<?php $this_category = get_queried_object();

// if parent is 0, category is top level
if( 0 == $this_category->parent ) :

    // top level category,
    // show child categories of this issue
    $args = array(
        'child_of' => $this_category->term_id,
        'title_li' => '',
        'hide_empty' => 0
    ); ?>

    <!-- output a list of child cats for this issue
    see also get_categories or get_terms if you wish to use your own markup-->


    <?php wp_list_categories($args); ?>





<?php else :

    // child category,
    // show articles in this subcategory, etc.
    echo 'child category';

endif; ?>
0

Get all children categories using get_terms(). Loop through each term and run a new query using tax_query.

Example:

<?php if ( get_queried_object()->parent == 0 ) :  // parent cat ?>
    <h2>Showing all children</h2>
    <?php
        $args = array(
            'hide_empty' => false,
            'parent' => get_queried_object()->term_id
        );
        $terms = get_terms( 'category', $args );

        if ( $terms ) echo '<ul>';
        foreach( $terms as $term ) {
            $the_post = new WP_Query(array(
                'posts_per_page' => 1,
                'tax_query' => array(
                    array(
                        'taxonomy' => 'category',
                        'field' => 'id',
                        'terms' => $term->term_id
                    )
                )
            ));
        ?>
            <?php while ( $the_post->have_posts() ) : $the_post->the_post(); ?>
                <li><a href="<?php echo get_term_link( $term, 'category'); ?>"><?php echo $term->name; ?></a> (Last article: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>)</li>
            <?php endwhile; wp_reset_query(); ?>
        <?php
        } //endforeach
        if ( $terms ) echo '</ul>';
    ?>

<?php else: // child ?>
    <?php
    while ( have_posts() ) : the_post();
        get_template_part( 'content', get_post_format() );
    endwhile;
    ?>
<?php endif; ?>
  • Hi Daniel, thats brilliant thank you! When i can upvote i will make sure i do. – dodgerogers Nov 5 '12 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.