如果is_array没有按预期的wordpress子类别工作

This code works fine and returns the sub-categories in the array, and does not return a result if there are not any subcategories,

 $parentCatName = single_cat_title('',false);
    $parentCatID = get_cat_ID($parentCatName);
    $childCats = get_categories( 'child_of='.$parentCatID );
    if(is_array($childCats)):
      foreach($childCats as $child){ ?>
     <?php query_posts('cat='.$child->term_id . '&posts_per_page=1');
         while(have_posts()): the_post(); $do_not_duplicate = $post->ID; ?>
    <!-- POST CODE -->
    <?php get_template_part( 'content', 'thumbs' ); ?>
    <!-- END POST CODE -->
    <?php
    endwhile;
    wp_reset_query();
    }
    endif;
    ?> 

however if I try to insert a header after the if is array, it returns the header whether there is a sub-category or not ie:

$parentCatName = single_cat_title('',false);
$parentCatID = get_cat_ID($parentCatName);
$childCats = get_categories( 'child_of='.$parentCatID );
if(is_array($childCats)):
echo 'Sub-Categories:' ;
  foreach($childCats as $child){ ?>
 <?php query_posts('cat='.$child->term_id . '&posts_per_page=1');
     while(have_posts()): the_post(); $do_not_duplicate = $post->ID; ?>
<!-- POST CODE -->
<?php get_template_part( 'content', 'thumbs' ); ?>
<!-- END POST CODE -->
<?php
endwhile;
wp_reset_query();
}
endif;
?>

I solved it by using count, but it seems clumsy to me and that it should have worked with if is array.

  <?php
    $parentCatName = single_cat_title('',false);
    $parentCatID = get_cat_ID($parentCatName);
    $childCats = get_categories( 'child_of='.$parentCatID );
    $countChild = count($childCats);
    if ($countChild > 0) : echo '<h2>Sub-Categories:</h2>'; endif;
    if(is_array($childCats)):
      foreach($childCats as $child){ ?>
     <?php query_posts('cat='.$child->term_id . '&posts_per_page=1');
         while(have_posts()): the_post(); $do_not_duplicate = $post->ID; ?>
    <!-- POST CODE -->
    <?php get_template_part( 'content', 'thumbs' ); ?>
    <!-- END POST CODE -->
    <?php
    endwhile;
    wp_reset_query();
    }
    endif;
    ?>

As stated in the comments the problem is not that is_array() is not working, the problem is you are not testing to see if the array has any rows.

Your way of doing it is just fine. There is no way of doing it that does not require to execute code. If I were doing it I would probably short circuit the IF statement like this:

if (is_array($childCats) and count($childCats)>0) {
    ...
}

That way you skip echoing out the header and the bother of the foreach - which right now is hitting and not executing because the array is empty.

HTH,

=C=