0

I want to show only the sub-categories from a post's specific parent category and exclude all the other categories.

This is for a loop of recent posts on my front-page.php. Each recent post is currently listing its categories using get_the_category_list($post->ID).

I tried get_the_category_list($parent, '8') but it didn't exclude anything. 8 is the integer of the parent category I want to keep. Any help is much appreciated!

Here's my code:

<?php $the_query = new WP_Query(array(
    'post_type'      => 'post',
    'category_name'  => 'genres',
    'posts_per_page' => 6,
    'post_status'    => 'publish'
    ));

    while ( $the_query->have_posts() ) : $the_query->the_post();

        echo '<div class="wrapper">
            <div> // stuff with post title, image and excerpt </div> 
            <div>' . get_the_category_list( $post->ID ) . '</div>';

    endwhile;
    wp_reset_postdata(); ?>

I want to go from this:

Parent-category 1, Sub-category 1 , Parent-category 2, Sub-category 2, Parent-category 3, Sub-category 3

To this:

Sub-category 1

0

I was able to find a function that worked found here.

First, I added the below code to my functions.php, which excludes the parent categories I do not want:

function custom_get_the_category_list() {
    $categories = get_the_category();
    $exclude1 = get_cat_ID( 'Parent1' );
    $exclude2 = get_cat_ID( 'Parent2' );
    $categories_list = '';

    foreach ( $categories as $category ) {
        if ( $category->category_parent == $exclude1
                || $category->cat_ID == $exclude1 || $category->category_parent == $exclude2
                || $category->cat_ID == $exclude2  ) {
            continue;
        }
        $categories_list .=
            '<li><a href="' . get_category_link( $category->cat_ID ) . '">' .
            $category->name .
            '</a></li>';
    }

    return '<ul class="post-categories">' . $categories_list . '</ul>';
}

And then in my loop, instead of using get_the_category_list($post->ID), I used the new function custom_get_the_category_list().

It certainly works, but if anyone finds a simpler solution please post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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