0

I'm building a plugin to show message based on which category user is browsing. For that I want to get all categories and I'm getting all categories by running:

$all_categories = get_categories(array('hide_empty' => false ));
$all_category_ids = array();
foreach($all_categories as $category)
{       
    array_push($all_category_ids, $category->term_id);    
}

Then I'm getting sub categories which I want to hide using:

$exclude_categories = get_categories(array( 'child_of' => 55, 'hide_empty' => false ));
$exclude_category_ids = array();    
foreach($exclude_categories as $ex_cat)
{
    array_push($exclude_category_ids, $ex_cat->term_id); 
}

Then I'm getting the difference by:

$to_show = array_diff($all_category_ids,$exclude_category_ids)

This gets the job done but query monitor plugin showing that there is duplicate queries which i have by running get_categories() twice.

Is there better way of doing this?

1 Answer 1

0

Since your first get_categories call will load all terms into memory, you can just loop over 'em and check if they have an ancestor with ID 55, and WordPress won't ever hit the db again:

$terms = get_terms([
     'taxonomy'   => 'category',
     'hide_empty' => false,
]);

foreach ( $terms as $k => $term ) {
    if ( in_array( 55, get_ancestors( $term->term_id, 'category', 'taxonomy' ) ) )
        unset( $terms[ $k ] );
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.