更高效地按类别列出帖子

时间:2015-02-02 作者:ideaotel

我有一个页面,列出了按类别分组的帖子。以下是当前代码:

<?php

$cats = get_terms(\'category\');

foreach ($cats as $cat) {
    $cat_id= $cat->term_id;

    echo "<h2>".$cat->name."</h2>";

    $custom_query = new WP_Query(
        array(
            \'cat\' => $cat_id,
            \'post_type\' => \'my_post_type\',
            \'posts_per_page\' => -1,
            \'orderby\' => \'title\',
            \'order\' => \'ASC\'
        )
    ); ?>
    <ul>
    <?php if ($custom_query->have_posts()) : while ($custom_query->have_posts()) : $custom_query->the_post(); ?>
        <li><a href="<?php the_permalink();?>"><?php the_title(); ?></a></li>
    <?php endwhile; endif; ?>
    </ul>

<?php } ?>
有没有一种更有效的方法可以在没有这么多查询的情况下做到这一点?我发现了这个相关的问题:Most efficient way to list all categories and display a post for each of them?. 然而,我不知道如何实施米洛的建议,也不知道它是否适用。

1 个回复
最合适的回答,由SO网友:Renato Gomes 整理而成

我的建议是将不同的参数传递给Wp\\u查询类。

使用“cat”属性,传递类别ID。

<?php
    $custom_query = new WP_Query(
        array(
            \'cat\' => \'1,2,3,4\'
            \'post_type\' => \'my_post_type\',
            \'posts_per_page\' => -1,
            \'orderby\' => \'title\',
            \'order\' => \'ASC\'
        )
    ); 
?>
或使用“category\\u name”属性将类别slug作为字符串参数传递。

<?php
    $custom_query = new WP_Query(
        array(
            \'category_name\' => \'category1+category2\'
            \'post_type\' => \'my_post_type\',
            \'posts_per_page\' => -1,
            \'orderby\' => \'title\',
            \'order\' => \'ASC\'
        )
    ); 
?>
有关Wp\\U查询参数的详细信息:http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

希望有帮助。祝你好运收件人:

结束

相关推荐

Loop returning only 1 result

我不知道为什么在运行循环时只返回1个结果。这是我的代码: <?php if ( is_front_page() && twentyfourteen_has_featured_posts() ) { // Include the featured content template. get_template_part( \'featured-content\' ); }