这可以通过ne walker类完成
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 );
}
}
}
必须将类作为参数传递给
wp_list_categories
$cat2post = new Childcat2LastPost();
$args = array(
\'walker\' => $cat2post
);
echo \'<ol>\';
wp_list_categories( $args );
echo \'</ol>\';
注释掉该行
\'post__not_in\'
如果您想包含粘性帖子。调整HTML,使其与
$output .= sprintf( \'<li><a href="%s">%s</a></li>\', esc_attr( $permlink ), esc_html( $title ) );
(添加
alt
和/或
title
属性、类等)。