如何在父类别页面上显示子类别内容?

时间:2012-02-02 作者:Bagger

我有一个WordPress网站,它有一个类别和两个子类别。

现在,如何在父类别上显示内容(子类别项目/内容)?

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

一种可能性:

<?php 
    $sub_cats = get_categories(\'parent=\' . get_query_var(\'cat\'));
    if( $sub_cats ) :
        foreach( $sub_cats as $sub_cat ) :
            $sub_query = new WP_Query( array(
                \'category__in\' => array( $sub_cat->term_id ),
                \'posts_per_page\' => -1)
            );
            if ( $sub_query->have_posts() ) :
                while( $sub_query->have_posts() ) : $sub_query->the_post();
                    //your output//
                endwhile;
            endif;
        endforeach;
    endif;
?>
http://codex.wordpress.org/Function_Reference/get_categorieshttp://codex.wordpress.org/Class_Reference/WP_Query

SO网友:mor7ifer

$cat = get_query_var( \'cat\' );
$args = array(
    \'post_status\' => \'publish\',
    \'tax_query\'   => array(
        array(
            \'taxonomy\' => \'category\', //may be categories, I never remember, try both
            \'field\'    => \'slug\', //may need to use ID, depends on output
            \'terms\'    => $cat
            //children are included by default
        )
    )
);
$posts = new WP_Query( $args );
这将为您提供一个post对象数组。您可以使用setup_postdata() 如果你想的话,把它输入到一个循环中。当您添加子类别时,此代码将是可扩展的,它们也将被查询。

文档:WP_Query, setup_postdata()

更新

<?php
$cat = get_query_var( \'cat\' );
$args = array(
    \'post_status\' => \'publish\',
    \'tax_query\'   => array(
        array(
            \'taxonomy\' => \'category\', //may be categories, I never remember, try both
            \'field\'    => \'id\', //may need to use slug, depends on output
            \'terms\'    => $cat
            //children are included by default
        )
    )
);  
$my_posts = new WP_Query( $args );
?>

<?php if ( $my_posts->have_posts()) : while ( $my_posts->have_posts() ) : $my_posts->the_post(); ?>     
    <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
        <div class="entryCategory">              
            <a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_post_thumbnail( \'thumbnail\', array( \'class\' => \'alignright\' ) ); ?></a>
        </div>

结束