0

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?

1

1 Answer 1

0

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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