我在我的网站上创建了一个页面,只需使用以下命令列出一个类别中的所有子类别:
<?php
$args = array(
\'show_option_all\' => \'\',
\'child_of\' => 8,
\'order\' => \'DESC\',
\'orderby\' => \'ID\'
);
$categories = get_categories($args);
foreach ($categories as $category) {
echo \'<a href="\' . get_category_link($category->term_id) . \'" title="\' . sprintf(__("View all posts in %s"), $category->name) . \'" \' . \'>\' . $category->name . \'</a> <br>\';
}
?>
我试图在括号中的名字后面加上最近一篇文章的日期,但似乎想不出一个方法。
编辑:使其正常工作
<?php
// select all sub categories of parent cat with id \'8\'
$categories = get_categories([\'parent\' => 8,\'orderby\' => \'ID\',\'order\' => \'DESC\',]);
// For each sub category find last post
foreach ( $categories as $category ) {
$args = array(
\'cat\' => $category->term_id,
\'post_type\' => \'post\',
\'posts_per_page\' => \'1\',
\'orderby\' => \'date\',
\'order\' => \'DESC\'
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
echo \'<a href="\' . get_category_link($category->term_id) . \'" title="\' . sprintf(__("View all posts in %s"), $category->name) . \'" \' . \'>\' . $category->name . \' (\'. get_the_date( "F j, Y", get_the_id() ) .\')</a> <br>\';
}
} else {
echo \'<a href="\' . get_category_link($category->term_id) . \'" title="\' . sprintf(__("View all posts in %s"), $category->name) . \'" \' . \'>\' . $category->name . \'</a> <br>\';
}
wp_reset_postdata();
}
?>
最合适的回答,由SO网友:lukgoh 整理而成
<?php
// select all sub categories of parent cat with id \'8\'
$categories = get_terms( \'category\', array(
\'orderby\' => \'ID\',
\'parent\' => 8
)
);
// For each sub category find last post
foreach ( $categories as $category ) {
$args = array(
\'cat\' => $category->term_id,
\'post_type\' => \'post\',
\'posts_per_page\' => \'1\',
\'orderby\' => \'date\',
\'order\' => \'DESC\'
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
echo \'<a href="\' . get_category_link($category->term_id) . \'" title="\' . sprintf(__("View all posts in %s"), $category->name) . \'" \' . \'>\' . $category->name . \' (\'. get_the_date( ** FORMAT HERE **, get_the_id() ) .\')</a> <br>\';
}
} else {
echo \'<a href="\' . get_category_link($category->term_id) . \'" title="\' . sprintf(__("View all posts in %s"), $category->name) . \'" \' . \'>\' . $category->name . \'</a> <br>\';
}
wp_reset_postdata();
}
?>