0

In this function, I need to exclude any categories from $categories which are children of "Uncategorized".

function get_cats(){
    $post_cats= array();
    $categories = get_the_category();
    foreach($categories as $cat){  
        array_push($post_cats, $cat->cat_ID);
    }
    return $post_cats;
}

Thanks in advance if you can help.

1

Check if $cat->category_parent != 1 (assuming uncategorized has the default ID of 1). If your subcategories are deeper than one level you'll need to use get_ancestors to determine the top level category.

1

It should be like this,

function get_cats(){
$post_cats= array();
$categories = get_the_category();
  foreach($categories as $cat){
     if($cat->category_parent == 1 || $cat->cat_ID == 1)
     continue;
     array_push($post_cats, $cat->cat_ID);
  }
return $post_cats; }

Now the Un-categorized category and with this children filtered. You can remove this category from the admin if you need.

Check this blog

0

I believe this can help (inside foreach):

if( $cat->cat_name != 'Uncategorized' ) {
    array_push( $post_cats, $cat->cat_ID );
}

Update:

You may want to use post_is_in_descendant_category function:

if( $cat->cat_name != 'Uncategorized'
    && !post_is_in_descendant_category(
           get_term_by( 'name', 'Uncategorized', 'category' ),
           $post
        )
) {
    array_push( $post_cats, $cat->cat_ID );
}

(not tested, sorry)

Nothe, that post_is_in_descendant_category should be defined in your functions.php, please check the link.

  • Thanks brownian, will this exclude the child cats of uncategorized too? Or do they have to be explicitly included by name as well? – N2Mystic Nov 20 '11 at 18:49
  • @N2Mystic i've updated the answer – brownian Nov 21 '11 at 7:39

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.