1

I am new to both php and wordpress. I have made some successful modifications in a child theme of Decode, but this is my first shot at a plugin. I'm trying to display a list of posts drawn from the same child category as the current post. I can produce a list of posts in the same parent category, but I can't figure out how to restrict the results of my query to the lowest level (child) category. The code below displays the type of list that I want but doesn't make the category restriction I'm looking for, and always displays an exact duplicate of the list directly under it. Any help would be greatly appreciated!

<?php

function list_subcategory_posts() {

    $post_id = get_the_ID();
    $categories = get_the_category();

    foreach ($categories as $category) {
        if (0 != $category->parent)
            $child_cat = $category;
        $current_post_type = get_post_type($post_id);

        $args = array(
            'category__in' => $child_cat,
            'post_type' => $current_post_type,
            'posts_per_page' => '5',
            'post__not_in' => array( $post_id )
        );

        $query = new WP_Query($args);

        if ( $query->have_posts() ) { ?>

            <aside class="related-posts">
                <h3>
                    <?php _e('Related Items', 'decode'); ?>
                </h3>
                <ul class="related-posts">
                    <?php while ( $query->have_posts()) { $query->the_post(); ?>
                        <li>
                            <a href="<?php the_permalink(); ?>">
                                <?php the_title(); ?>
                            </a>
                        </li>
                    <?php } ?>
                </ul>
            </aside>
        <?php }
        wp_reset_postdata();
    }
}

add_action('related_posts', 'list_subcategory_posts');
?>

1 Answer 1

2

I just figured this one out by modifying the first foreach statement.

$post_id = get_the_ID();
$cat_ids = array();
$categories = get_the_category();

 if ( $categories && !is_wp_error( $categories ) ) {

foreach( $categories as $category ) {
        if( 0 == $category->parent )
            {
             continue;
       }else{
              array_push( $cat_ids, $category->term_id ); 
            }
            $current_post_type = get_post_type( $post_id );

         $args = array(
            'category__in' => $cat_ids,
            'post_type' => $current_post_type,
            'posts_per_page' => '5',
            'post__not_in' => array( $post_id )
           );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.