PhatToni
PhatToni

Reputation: 105

Check if a parent category has a parent category?

I have checked if a category 'categoryone' has a parent category, and Yes categoryone have a parent category called categorydad, know I wanna check if categorydad has a parent...

$tid = term_exists('categoryone', 'category', 0);

    $term_ids = array();

    if ( $tid !== 0 && $tid !== null )
    {
        $term_ids[] = $tid['term_id'];
    }
    else
    {
        // Finns inte!
        $insert_term_id = wp_insert_term( 'categoryone', 'category' );

        // var_dump( $insert_term_id );

        if ( ! is_wp_error )
            $term_ids[] = $insert_term_id;

    }
    wp_set_post_categories( $insert_id, $term_ids );

Upvotes: 1

Views: 1217

Answers (1)

Nisarg Patel
Nisarg Patel

Reputation: 260

function category_has_parent($catid){
    $category = get_category($catid);
    if ($category->category_parent > 0){
        return true;
    }
    return false;
}

if (category_has_parent('22')){
    //true there is a parent category
}else{
   //false this category has no parent
}

To check the other way around (if a category has children) you can use get_categories

$children = get_categories(array('child_of' => id,'hide_empty' => 0));
if (count($children) > 1){
    //has childern
}else{
    //no children
}

OR check this : http://alex.leonard.ie/2011/04/20/wordpress-get-id-of-top-level-parent-category/

Upvotes: 1

Related Questions