0

So I'm having trouble printing just the direct children of a category on a page. Here's my code:

 $category_id = get_cat_ID('destinations');
 $args = array('child_of'   => $category_id);
 $categories = get_categories($args);
 $args = array (
    'category__and'                    => $categories->$cat_ID
);
   $recent_posts = new WP_Query($args);
if ($recent_posts->have_posts())  : while ($recent_posts->have_posts()) : $recent_posts->the_post();

This code prints every category regardless of who's the parent. If I change this:

$recent_posts = new WP_Query('cat=43'); It prints out the right category, but also all of it's children and children's children(obviously). I just want the directly related children printed. I went ahead and echoed a serialize($categories) which returned the correct array. However when I serialize($args) AFTER the 2nd declaration, it gives me:

a:1:{s:13:"category__and";N;}

This is definitely weird. Why on Earth is it returning an 'N' for $categories->$cat_ID? I've been trying to do this all day and have been unsuccessful. I've also tried to find another method to do what I want but nothing came up.

Any ideas?

0

From the Codex:

 child_of 
    (integer) Display all categories that are descendants (i.e. children & grandchildren) of the category identified by its ID. There is no default for this parameter. If the parameter is used, the hide_empty parameter is set to false. 

And...

parent  
    (integer) Display only categories that are direct descendants (i.e. children only) of the category identified by its ID. This does NOT work like the 'child_of' parameter. There is no default for this parameter. [In 2.8.4]

So, first, you are using the wrong argument if you only want the immediate decendants. You need:

$args = array('parent'   => $category_id);

Secondly, get_categories will give you an array of objects so you will need something like this to extract the IDs.

$cats = wp_list_pluck($categories,'cat_ID');
$args = array (
  'category__and'                    => $cats
);

Giving you:

$category_id = get_cat_ID('destinations');
$args = array('parent'   => $category_id);
$categories = get_categories($args);
$cats = wp_list_pluck($categories,'cat_ID');
$args = array (
  'category__and'                    => $cats
);
$recent_posts = new WP_Query($args);

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.