Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am using wp_list_categories() to show all my categories. But I would like that the child categories link to the last post of that category. For example:

 <ul>
   <li><a href="link-to-category-1">CATEGORY 1</a> 
       <ul>
           <li><a href="link-to-last-post-of-category-1-1">CATEGORY 1.1</a></li>
      </ul>
  </li>
</ul>

How can I do it?

share|improve this question
    
What is the difference to this question? –  toscho Apr 28 '13 at 0:47
add comment

1 Answer

This could be done with a ne walker class

class Childcat2LastPost extends Walker_Category
{
    function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {

        if ( 0 != $category->category_parent ) {

            $args = array(
                    'cat'            => $category->term_id,
                    'orderby'        => 'post_date',
                    'order'          => 'DESC',
                    'post_type'      => 'post',
                    'post_status'    => 'publish',
                    'post__not_in'   => get_option( 'sticky_posts' ), // do not display sticky posts
            );

            $query        = new WP_Query( $args );
            $recent_posts = $query->get_posts();
            $last         = sizeof( $recent_posts ) -1;
            $last_post    = $recent_posts[$last];
            $permlink     = get_permalink( $last_post->ID );
            $title        = $last_post->post_title;

            if ( ! empty( $permlink ) ) {
                $output .= sprintf( '<li><a href="%s">%s</a></li>', esc_attr( $permlink ), esc_html( $title ) );
            }

        } else {

            parent::start_el( $output, $category, $depth, $args, $id );

        }

    }
}

You have to pass the class as argument to wp_list_categories

$cat2post = new Childcat2LastPost();

$args = array(
    'walker' => $cat2post
);

echo '<ol>';
wp_list_categories( $args );
echo '</ol>';

Comment out the line 'post__not_in' if you want to include sticky posts. Adjust the HTML in the line with $output .= sprintf( '<li><a href="%s">%s</a></li>', esc_attr( $permlink ), esc_html( $title ) ); (add an alt and/or title attribute, a class etc).

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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