0

I am trying to get the category ID of the child (no grand children) of the current category. Using below method:

$category = get_category(get_query_var( 'cat' ));
// get category ID
$catid = $category->cat_ID;

I can get the current category ID. However, using this in WP_Query result in displaying the posts that are published in Parent, Child, Grand Child category.

Is there any way, to get the child category ID of the current category?

Update #1:

Sample category structure is as follow:

- Parent Category x
-- Child One
--- Grand Child one
--- Grand Child two
-- Child Two
--- Grand Child one
--- Grand Child two

once in the Parent Category x we have the ID, now I want the Child Category id. Once in Child Category x, I want the Grand Child Category id to be used in :

wordpresss/category/parent       : posts published in child category 
wordpresss/category/parent/child : posts published in grand child category
  • is this on a category archive page? – Milo Oct 30 '15 at 19:39
  • @milo yes, I am trying to create a custom query which displays posts published under the sub category (not the parent or grand child category) – Rain Man Oct 30 '15 at 19:40
  • so, there are multiple levels of child categories under the parent and you only want the level directly below? – Milo Oct 30 '15 at 19:42
  • @Milo I updated the question, but basically yes, the below category of current category – Rain Man Oct 30 '15 at 19:49
1

Use get_terms with parent argument to get only direct children of a term. Use wp_list_pluck to extract an array of term IDs that can be passed to a query.

$args = array(
    'parent' => get_queried_object_id(),
); 

$terms = get_terms( 'category', $args );

$term_ids = wp_list_pluck( $terms, 'term_id' );

Also uses get_queried_object_id to get the ID of the current category archive.

  • so something like this ? – Rain Man Oct 30 '15 at 20:00
  • $term_ids is already an array, no need to wrap it in array(). – Milo Oct 30 '15 at 20:01
  • nice, it worked :) one quick question, is it possible to test if we are in the last category so instead of linking to category we link to post? – Rain Man Oct 30 '15 at 20:02
  • You can check if $terms is empty, there are no child terms. – Milo Oct 30 '15 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.