Search code examples
wordpresscustom-post-type

Get category id of custom post type in archive page


I have custom taxonomy and category like this :

products_categories
    cat-1
         cat-1 
              post-1   post-2    post-3
         cat-2 
              post-1   post-2    post-3
         cat-3 
              post-1   post-2    post-3
    cat-2
         cat-1 
              post-1   post-2    post-3
         cat-2 
              post-1   post-2    post-3
         cat-3 
              post-1   post-2    post-3

I want to make an archive page to:

  • query all the category of that custom taxonomy;
  • then query all the post of those category.

Here is my archive:

First:

$args = array(
'type'              => 'products',       
'taxonomy'          => 'products_categories',    
$categories = get_categories( $args );

Second:

<? foreach ( $categories as $category ):
$cat_id = $category->term_id;
$cat_name = $category->cat_name;
?>

Third:

<?php
$cats_id= array();
foreach ( $sub_categories as $sub_category ) :
    $cats_id[]=$sub_category->term_id;
endforeach;

$args = array(
 'posts_per_page' => -1,
 'orderby' => 'rand',
 'post_type' => 'products',
 'post_status' => 'publish',
 'tax_query' => array(
   array(
   'taxonomy' => 'products_categories',
   'field' => 'id',
   'terms' => $cats_id,
   ),
));

$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
?>

And it's ok. I get all the post of those sub-category of the parent category;

Now I want to get the category id of the post in last section.


Solution

  • The categories of the current post would be:

    get_the_terms()
    

    This returns an array of categories attached to the post.