2
votes

I have a custom post type called "categories" and it's slug is "category". I have various categories like:

  • Beauty
    • Makeup
    • Skincare
  • Tech

I have these categories in a CPT called "Products". I want to display only those posts that match with a subcategory. For example, I want to display only those posts from CPT "Products" that have "Makeup" checked in categories custom taxonomy. I have tried the following code:

$args= new WP_Query( array(
         'post_type' => 'Products',
         'tax_query' => array(
                        array (
                                'taxonomy' => 'categories',
                                'field' => 'slug',
                                'terms' => 'Beauty',
                            )
                        ),
           ) );
     if($args->have_posts()):
        while ($args->have_posts()):$args->the_post();
           echo get_field('name');
        endwhile; 
     endif;

But this code obviously displays posts that have category checked as "Beauty". It doesn't check for subcategory. Can anyone help me out with this? Any modification to the current code would be helpful as well. Thanks!

1
is this woocommerce products ?Angel Deykov
No. Products is just custom post type. The data fed into this cpt comes from a form on the front end.Komal R

1 Answers

1
votes

If you want to display posts from a certain subcategory you can simply use get_posts(), something like:

 $posts = get_posts(array(
    'post_type' => 'Products',
    'post_status'   => 'publish',
    'cat'      => your subcat ID,
    'posts_per_page'   => -1
));

And then loop through your posts like:

 foreach ($posts as $post){
     echo $post->post_title . '<br>';

 }