WordPress-列出子类别和子类别,带帖子

时间:2015-02-13 作者:pee2pee

我有以下代码。它允许我显示子类别和其中的文档。问题是,一个子类别可能包含更多的子类别。下面的代码将显示属于子(父)级别的子(孙子)类别的文档。

请任何人都能说明如何解决这个问题,以便文档只显示在他们直接所属的类别下面吗?此外,还要强调什么是子-子(孙子)类别?所有帖子标题都应链接到帖子

<?php
$categories =  get_categories(\'child_of=34\');  
foreach  ($categories as $category) {
    //Display the sub category information using $category values like $category->cat_name
    echo \'<h3>\'.$category->name.\'</h3>\';
    echo \'<ul>\';

    foreach (get_posts(\'cat=\'.$category->term_id) as $post) {
        setup_postdata( $post );
        echo \'<li><a href="\'.get_permalink($post->ID).\'">\'.get_the_title().\'</a></li>\';   
    }  
    echo \'</ul>\';
}
?>
下面是一些

第1子类第1子类第4子类第2子类第3子类

1 个回复
SO网友:vrajesh

Try This :

<!-- Category Archive Start -->
<ul class="catArchive">
<?php
$catQuery = $wpdb->get_results("SELECT * FROM $wpdb->terms AS wterms INNER JOIN $wpdb->term_taxonomy AS wtaxonomy ON ( wterms.term_id = wtaxonomy.term_id ) WHERE wtaxonomy.taxonomy = \'category\' AND wtaxonomy.parent = 0 AND wtaxonomy.count > 0");

$catCounter = 0;

foreach ($catQuery as $category) {

    $catCounter++;

    $catStyle = \'\';
    if (is_int($catCounter / 2)) $catStyle = \' class="catAlt"\';

    $catLink = get_category_link($category->term_id);

    echo \'<li\'.$catStyle.\'><h3><a href="\'.$catLink.\'" title="\'.$category->name.\'">\'.$category->name.\'</a></h3>\';
        echo \'<ul style="margin-left:15px;">\';

        query_posts(\'category__in=\'.$category->term_id.\'&showposts=5\');?>

        <?php while (have_posts()) : the_post(); ?>
            <li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
        <?php endwhile; ?>

            <li><a href="<?php echo $catLink; ?>" title="<?php echo $category->name; ?>">More <strong><?php echo $category->name; ?></strong></a></li>
     <li> <?php
     $sub_cat_id = $category->term_id;
     $get_sub_args = array(\'child_of\' =>$sub_cat_id);
             $categories_arr =  get_categories($get_sub_args);  
             //print_r ($categories_arr);
    foreach  ($categories_arr as $sacategory) {
            //Display the sub category information using $category values like $category->cat_name
            echo \'<h2>\'.$sacategory->name.\'</h2>\';
            echo \'<ul style="margin-left:15px;">\';

            foreach (get_posts(\'cat=\'.$sacategory->term_id) as $post) {
                setup_postdata( $post );
                echo \'<li><a href="\'.get_permalink($post->ID).\'">\'.get_the_title().\'</a></li>\';   
            }  
            echo \'</ul>\';
        }

     ?></li>



        </ul>
    </li>
    <?php } ?>
</ul>
<!-- Category Archive End -->
    </div>
结束