列出给定类别中的帖子

时间:2019-11-23 作者:Jack

我正在使用此代码将所有帖子按字母顺序排列在给定的类别中,这是可行的,但我觉得代码可以改进。。。

<?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();
你觉得怎么样?

1 个回复
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();

相关推荐

Related Customs posts

也许有人可以帮助制作自定义帖子类型的相关帖子?我受不了了。。。代码在此处:https://pastebin.com/zRVjuMBnFor example:We are in current post:ID | title | cust\\u category | cust\\u names | cust\\u settings1 | X1 | cat1,cat3 | name8 | set1,set5And we have customs posts:ID | title | cust\\u categ