I am using this code to get all posts sorted alphabetically in a given category, it works, but I feel the code can be improved...
<?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();
What do you think?
I am using this code to get all posts sorted alphabetically in a given category, it works, but I feel the code can be improved...
<?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();
What do you think?
Share Improve this question edited Nov 23, 2019 at 13:17 Chetan Vaghela 2,4084 gold badges10 silver badges16 bronze badges asked Nov 23, 2019 at 5:52 JackJack 111 bronze badge1 Answer
Reset to default 1You are already passing category in $args
. so not need to use get_categories()
. You can use below code.
$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();