我正在使用WordPress开发一个网站和一个自制模板。我有一个页面显示所有类别及其帖子。这就是我想做的:
主类别子类别1后1子类别1。1.2.1后1.2.2后2wp_link_category() 为了显示类别,我搜索了如何使用帖子显示类别,但问题是:子类别1.2中的帖子也显示在子类别1上。
主类别子类别1后1.2.1后1.2.2后1子类别1。2发布1.2.1后,如何从子类别1的子类别1.2中删除帖子?
下面是我从StackOverflow复制和粘贴的代码:
$categories =  get_categories(\'child_of=4\');  
foreach  ($categories as $category) {
    //Display the sub category information using $category values like $category->cat_name
    echo \'<h2>\'.$category->name.\'</h2>\';
    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>\';
}
 我希望你能理解我。
 
                SO网友:Charles Clarkson
                如何从子类别1的子类别1.2中删除帖子?
使用\'category__in\' 参数,而不是\'cat\' 参数
这是一个用户函数,它可以满足您的需要。
/**
 * Category post list.
 *
 * An unordered list of category posts links. Posts in subcategories
 * are not listed in parent category. Skips categories with no posts.
 *
 * @param $parent_category The parent category to start with. Defaults to 0.
 */
function wpse_113987_category_post_list( $parent_category = 0 ) {
    $post_list_format = \'<li><a href="%s">%s</a></li>\';
    // Step through each category object.
    foreach ( get_categories( "child_of=$parent_category" )  as $category ) {
        $category_posts = get_posts( array(
            // Do not include posts in sub categories.
            \'category__in\'  => array( $category->term_id ),
        ) );
        // Skip categories with no posts.
        if ( empty( $category_posts ) )
            continue;
        echo "<h2>$category->name</h2>\\n";
        echo "<ul>\\n";
        // Step through each post object.
        foreach ( $category_posts as $post ) {
            printf( $post_list_format, get_permalink( $post->ID ), get_the_title( $post->ID ) );
        }
        echo "\\n</ul><!-- end $category->name -->\\n";
    }
}
 要调用它,请使用:
wpse_113987_category_post_list( 4 );