Bob Flemming
Bob Flemming

Reputation: 466

Exclude Wordpress posts from being shown on homepage from a specific category

Heres a tricky one...

If a post is marked as 'Category A' I want it to be excluded from the homepage. This can be achieved with the following code:

function exclude_category($query) 
{
    if ( $query->is_home() ) 
    {
        $query->set('cat', '-3804');
    }
    return $query;
}

add_filter('pre_get_posts', 'exclude_category');

BUT if a post is marked as 'Category A' AND 'Category B' I want it to show on the homepage. How can I tweak my code to allow for this?

Upvotes: 0

Views: 151

Answers (2)

Trishul
Trishul

Reputation: 1028

Hi just a top up to previous answer

function exclude_category($query) 
{
$categories = get_categories();
$catarray="";
foreach ($categories as $category) {
if ($category->cat_ID !="<your category ID>")
{
    $catarray .=$category->cat_ID.",";
}
    }
rtrim($catarray, ",");
if ( $query->is_home() ) 
{
    $query->set('cat', $catarray);
}

}
return $query;


add_filter('pre_get_posts', 'exclude_category');

Upvotes: 3

Koen de Bakker
Koen de Bakker

Reputation: 390

You probably thought of this, but not displaying if an item is ONLY in category A is the same as displaying every category except Category A;

function exclude_category($query) 
{
    if ( $query->is_home() ) 
    {
        $query->set('cat', 'B,C,D,E,F');
    }
    return $query;
}

add_filter('pre_get_posts', 'exclude_category');

Upvotes: 1

Related Questions