【问题标题】:Wordpress Display All Sub categorys + posts under Posts Child Category in SidebarWordpress 在侧边栏中的帖子子类别下显示所有子类别 + 帖子
【发布时间】:2013-03-10 16:29:31
【问题描述】:

抱歉标题太复杂了。

我正在使用此代码,以显示我的子子类别及其下的帖子。问题是代码显示了我在网站上拥有的所有子子类别(+ 帖子)。我只想显示与帖子相关的子类别。 Child one 下的所有子子类别都与帖子有关,因此您可以说我想显示 child on 下的子子类别,因为帖子与 child on 相关。

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

  • G
    • 儿童 1
      • 游戏第一年
        • 在这里发帖
      • 游戏年 2
        • 在这里发帖

我的代码:

<?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 );
    }
}

?>

有什么想法吗?

提前致谢!

【问题讨论】:

    标签: php wordpress categories sidebar


    【解决方案1】:

    我相信您得到了错误的类别 ID。你应该使用这个:

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

    代替

    $cat_id = get_query_var( 'cat' );
    

    【讨论】:

    • 感谢您的回复!好吧,它得到了正确的 cat_id,唯一的是它正在打印网站上的所有子子类别,我想打印与帖子相关的所有子类别,在这种情况下它是子子项的父项(子项 1) .我如何让代码做到这一点?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多