繁体   English   中英

WordPress在侧边栏的“帖子子类别”下显示所有子类别和帖子

[英]Wordpress Display All Sub categorys + posts under Posts Child Category in Sidebar

抱歉,标题复杂。

我正在使用此代码,以显示我的子子类别及其下的帖子。 问题在于代码显示的是我在网站上拥有的所有子子类别(+帖子)。 我只想显示与帖子相关的子类别。 “子一”下的所有子子类别均与帖子相关,因此您可以说我要在“子”下显示子子类别,因为该帖子与“子”上的关联。

类别结构(标题中为年份):

  • G
    • 儿童1
      • 游戏一年
        • 在此发布
      • 游戏第二年
        • 在此发布

我的代码:

<?php
$cat_id = get_query_var( 'cat' );
$subcats = get_categories( 'child_of=' . $cat_id ); // child categories

class Cat_Walker extends Walker_Category {
    function end_el( &$output, $page, $depth = 0, $args = array() ) {
        $posts = get_posts( 'cat=' . $page->term_id );

        if ( sizeof( $posts ) > 0 ) {
            $output .= '<ul>';

            foreach ( $posts as $post ) {
                $output .= sprintf( '<li><a href="%1$s">%2$s</a></li>', get_permalink( $post->ID ), $post->post_title );
            }

            $output .= '</ul>';
        }

        $output .= '</li>';
    }
}

foreach ( $subcats as $subcat ) {
    $subsubcats = get_categories( 'child_of=' . $subcat->term_id ); // sub child categories

    foreach ( $subsubcats as $subsubcat ) {
        $args = array(
            'title_li'         => '',
            'show_option_none' => '',
            'taxonomy'         => 'category',
            'child_of'         => $subsubcat->term_id,
            'walker'           => new Cat_Walker( )
        );

        wp_list_categories( $args );
    }
}

?>

有任何想法吗?

提前致谢!

我相信您输入的类别ID错误。 您应该使用此:

$category = get_category(get_query_var('cat'));
$cat_id = $category->cat_ID;

代替

$cat_id = get_query_var( 'cat' );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM