Can't seem to filter wp_query by current category ID

I'm querying a custom post type ("donor") and would like to list them grouped by category (a custom taxonomy for this post type), with the category title then all posts for that category.

After much research, I've got this (in my custom post type's archive template, archive-donor.php):

global $paged;
global $query_args;


$category_args = array(
'taxonomy' = 'donor_taxonomy',
'orderby' = 'name',
'parent' = 0
  );
$categories = get_categories( $category_args );
foreach ( $categories as $category ) {

echo 'h3a href="' . get_category_link( $category-term_id ) . '"' . $category-name . '/a/h3';  

echo 'ID is: ' . $category-term_id . '. ';

$post_args = array(
    'cat' = $category-term_id,
    'post_type' = 'donor',
    'orderby'       = 'post_date',
    'posts_per_page'= '-1', // overrides posts per page in theme settings

);

$loop = new WP_Query( $post_args );
if( $loop-have_posts() ) {

 [query stuff here that works fine when I do NOT try to specify the category in my query args]
} 

wp_reset_postdata();    
}

Even though I can echo the ID number with this line...

echo 'ID is: ' . $category-term_id . '. ';

...If I include the following with my $post_args, which uses the same code to extract the ID, it says no posts were found:

'cat' = $category-term_id

If I leave that line out, I get all posts regardless of category, listed after each category title. If I include it, I get "no posts found" after each title. The titles themselves display correctly in order.

I must be doing something wrong but can't for the life of me figure out what. Hope someone can help! 8^)

Topic wp-query categories custom-post-types Wordpress

Category Web


You mentioned you are using a custom taxonomy - therefore including the cat key in your wp_query args won't work. wp_query expects that to be the ID of a term belonging to the standard WP category taxonomy. With a custom tax you need to use the dedicated taxonomy parameters.

So your args should be something like:

$post_args = array(
    'post_type' => 'donor',
    'orderby'       => 'post_date',
    'posts_per_page'=> '-1', // overrides posts per page in theme settings
    'tax_query' => array(
        array(
            'taxonomy' => 'donor_taxonomy',
            'field'    => 'term_id',
            'terms'    => $category->term_id,
        ),
    )

);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.