WordPress.org

Ready to get started?Download WordPress

Forums

Display related posts by category in sidebar (1 post)

  1. Livog
    Member
    Posted 1 year ago #

    Hi I am trying to display related posts in the sidebar.

    My category structure:

    - G
    -- Child 1
    --- Sub Child 1
    --- Sub Child 2
    --- Sub Child 3
    -- Child 2
    --- Sub Child 4
    --- Sub Child 5

    Okay so if the post is under Sub Child 2, I want to display all the posts under sub child 1 & 3 aswell ( all sub childs under child 1) My code below show sub child 4 and 5 aswell (all sub child registered on the website) So if the post is related to the parent of the sub child, how do I make my code display the other sub childs with post under them.

    Thanks in advance

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

Topic Closed

This topic has been closed to new replies.

About this Topic