使用wp_list_ategories显示多个类别中的最后一篇帖子

时间:2012-11-05 作者:dodgerogers

我有以下代码,当您单击父类别时,它会在单独的页面上列出子类别。代码呈现如下列表:

主页›IQ第7期存档

日志

新闻

世界观

然而,我想从每个类别中检索最新的帖子,并打印在类别名称下面。我如何在下面的循环中实现这一点?我尝试了几个foreach循环,但似乎都没有打印出正确的信息。提前谢谢。

类别php

<?php $this_category = get_queried_object();

// if parent is 0, category is top level
if( 0 == $this_category->parent ) :

    // top level category,
    // show child categories of this issue
    $args = array(
        \'child_of\' => $this_category->term_id,
        \'title_li\' => \'\',
        \'hide_empty\' => 0
    ); ?>

    <!-- output a list of child cats for this issue
    see also get_categories or get_terms if you wish to use your own markup-->


    <?php wp_list_categories($args); ?>





<?php else :

    // child category,
    // show articles in this subcategory, etc.
    echo \'child category\';

endif; ?>

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

使用获取所有子类别get_terms(). 循环遍历每个术语,并使用tax_query.

示例:

<?php if ( get_queried_object()->parent == 0 ) :  // parent cat ?>
    <h2>Showing all children</h2>
    <?php
        $args = array(
            \'hide_empty\' => false,
            \'parent\' => get_queried_object()->term_id
        );
        $terms = get_terms( \'category\', $args );

        if ( $terms ) echo \'<ul>\';
        foreach( $terms as $term ) {
            $the_post = new WP_Query(array(
                \'posts_per_page\' => 1,
                \'tax_query\' => array(
                    array(
                        \'taxonomy\' => \'category\',
                        \'field\' => \'id\',
                        \'terms\' => $term->term_id
                    )
                )
            ));
        ?>
            <?php while ( $the_post->have_posts() ) : $the_post->the_post(); ?>
                <li><a href="<?php echo get_term_link( $term, \'category\'); ?>"><?php echo $term->name; ?></a> (Last article: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>)</li>
            <?php endwhile; wp_reset_query(); ?>
        <?php
        } //endforeach
        if ( $terms ) echo \'</ul>\';
    ?>

<?php else: // child ?>
    <?php
    while ( have_posts() ) : the_post();
        get_template_part( \'content\', get_post_format() );
    endwhile;
    ?>
<?php endif; ?>

结束

相关推荐

How to do paging in the loop?

我用过single.php 对于此代码:<?php $categories = get_the_category($post->ID); if ($categories) { $category_ids = array(); foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id; $args=array