Tonmoy
Tonmoy

Reputation: 307

how to get only parent category posts in wordpress

I want to get the only top parent categories(cat_id=1) list in the front page. For that I have written this While loop in home page.

<div class="left col-xs-12 col-md-8 col-lg-9">
        <?php
            while(have_posts()) {
                the_post(); ?>
                <div class="content-block col-xs-12">
                    <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                    <hr class="color-strip">
                    <p><?php echo wp_trim_words(get_the_content(), 11); ?></p>
                    <p><a href="<?php the_permalink(); ?>">Continue reading &raquo;</a></p>
                    <div class="tags"><ul><li><?php the_tags(); ?></li></ul></div>
                </div>
                <hr/>
        <?php }?>

    </div>

But its bringing all the subcategories also. I want to keep the list of only one category. What change do I have to make in the if condition.

Upvotes: 1

Views: 5965

Answers (2)

mcon
mcon

Reputation: 664

You can get the categories using get_categories() and you can get all of the top level categories with:

$categories = get_categories(
    array(
        'parent' => 0
    )
);

Then, something like this should work for you to get only posts within top level categories.

$categories = get_categories(
    array(
        'parent' => 0
    )
);

$categoryArray = array();

foreach( $categories as $category ) {
    $categoryArray[] = $category->ID;
}

function exclude_category($query) {
    if ( $query->is_home() ) {
        $query->set( 'cat', implode(',', $categoryArray) );
    }
    return $query;
}
add_filter('pre_get_posts', 'exclude_category');

This will get all of the top level categories and then set them in the main query.

Upvotes: 2

Tonmoy
Tonmoy

Reputation: 307

the Following cod partially fixes my problem. Writing a function in functions.php.

function exclude_category($query) {
    if ( $query->is_home() ) {
    $query->set('cat', '-5,-6');
    }
    return $query;
    }
    add_filter('pre_get_posts', 'exclude_category'); 

Upvotes: 0

Related Questions