Im trying to check if 'categoryone' has a parent. Right know I can check and see that there is a category called categoryone, but not if categoryone has a parent category. I have tried to code something like the code bellow.
$tid = term_exists('categoryone', 'category', 0);
$term_ids = [];
if ( $tid !== 0 && $tid !== null )
{
$term_ids[] = $tid['term_id'];
}
else
{
// If there is not a parent category!
$insert_term_id = wp_insert_term( 'categoryone', 'category' );
if ( ! is_wp_error )
$term_ids[] = $insert_term_id;
}
wp_set_post_categories( $insert_id, $term_ids );
The variable $cat is the category ID you are checking: Use this function cat_has_subcat ('paste cat id') to check the category has any subcategories or not Thanks for contributing an answer to WordPress Development Stack Exchange! Please be sure to answer the question.
The variable $cat is the category ID you are checking: $categories = get_categories ($cat); if (!empty ($categories)) { // This Category has children } else { // This category has no children }
You can simply now just pass the term id to the function and the correct taxonomy name if the taxonomy is anything other than category, and you will get a boolen value back just as the build in conditional tags, true on success if the term have children, false if it does not.
You may use something like this (Paste this in your functions.php
file)
function category_has_parent($catid){
$category = get_category($catid);
if ($category->category_parent > 0){
return true;
}
return false;
}
Call this from template
if(category_has_parent($tid)) {
// it has a parent
}
Check Children
function has_Children($cat_id)
{
$children = get_terms(
'category',
array( 'parent' => $cat_id, 'hide_empty' => false )
);
if ($children){
return true;
}
return false
}
Call this from template
if(has_Children($tid)) {
// it has children
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With