Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

How to exclude categories from wp_query with get_the_category? WordPress

  • SOLVED


Hi,

I would appreciate some help here. below is what I have so far. I have a custom post type (projects) and I'm using this code to get the current category. The problem is that it gets the first category that the post is in so if it's in 'featured items' for example it will display all the posts in that category rather than 'houses' which is the current category.

I suppose I'm looking for a way to exclude some categories. Does anyone have a solution?

<?php
global $post;
$categories = get_the_category();
$category = $categories[0];
$cat_ID = $category->cat_ID;

$custom_query = new WP_Query( array( 'post_type' => 'projects', 'cat' => $cat_ID ) ); ?>

<?php while($custom_query->have_posts()) : $custom_query->the_post(); ?>


Thanks in advance

Answers (1)

2012-07-30

Arnav Joy answers:

to exclude category you can use

cat => -1 // where 1 is the catergory id to exclude , see below

<?php $custom_query = new WP_Query( array( 'post_type' => 'projects', 'cat' => '-1,-2,3' ) );?>


Arnav Joy comments:

if you want to display the posts from current category then you can use

<?php $custom_query = new WP_Query( array( 'post_type' => 'projects', 'cat' => get_query_var('cat') ) ); ?>


stickybeak comments:

Thanks Arnav,

However I've used '$cat_ID' as their are many categories sharing this template and each post is within multiple categories.
I need a way to list posts from only that category and to exclude some set ones.

I used this to get the current category as a standard wp_query didn't seem to work. I presumed it had something to do with it querying a category in a custom post type.

This is pushing my knowledge limits so please be patient with me if I'm not describing it correctly.

<?php
global $post;
$categories = get_the_category();
$category = $categories[0];
$cat_ID = $category->cat_ID;

$custom_query = new WP_Query( array( 'post_type' => 'projects', 'cat' => $cat_ID ) ); ?>


Arnav Joy comments:

try using my second solution..

can you tell me in which page you are showing posts

category.php , archieve.php , index.php or any template-page.php

???


stickybeak comments:

The second solution works. Many Many thanks :-)