最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - List posts in a given category

programmeradmin3浏览0评论

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 badge
Add a comment  | 

1 Answer 1

Reset to default 1

You 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();
发布评论

评论列表(0)

  1. 暂无评论