我正在使用此代码将所有帖子按字母顺序排列在给定的类别中,这是可行的,但我觉得代码可以改进。。。
<?php
$cats = get_categories(\'include=5\');
foreach ($cats as $cat) {
echo "<ul>";
$args = array(
\'cat\' => 5,
\'posts_per_page\' => -1,
\'orderby\' => \'title\',
\'order\' => \'ASC\'
);
$custom_loop = new WP_Query($args);
while ($custom_loop->have_posts()) {
$custom_loop->the_post();
$category = get_the_category();
// Only display a post link once, even if it\'s in multiple categories
if ($category[0]->cat_ID == $cat->cat_ID) {
echo \'<li><a href="\' . get_permalink() . \'">\' . get_the_title() . \'</a></li>\';
}
}
echo "</ul>";
}
wp_reset_query();
你觉得怎么样?
SO网友:Chetan Vaghela
您已传入类别$args
. 所以不需要使用get_categories()
. 您可以使用以下代码。
$args = array(
\'cat\' => 5,
\'posts_per_page\' => -1,
\'orderby\' => \'title\',
\'order\' => \'ASC\'
);
$custom_loop = new WP_Query($args);
if ($custom_loop->have_posts()) {
echo "<ul>";
while ($custom_loop->have_posts()) {
$custom_loop->the_post();
echo \'<li><a href="\' . get_permalink() . \'">\' . get_the_title() . \'</a></li>\';
}
echo "</ul>";
}
wp_reset_query();