functions – How to get taxonomy tree ids without running expensive loops

Question

I’m in the middle of building a importer that uses WC API to import products, i’ve run into an issue where i need to add custom taxonomy tree to the product by ids but i can’t figure out how to accomplish that without running expensive loops.

I have a list of taxonomy tree names eg. Parent->Child->Grandchild, i need to replace these names with the corresponding ID eg. 12312->324234->2343243 so that the wordpress knows which taxonomy terms are related to the product.

The problem is every product has a hundred+ possible term combinations and in the database we have over 80k terms to compare it with. There are also many terms that are named the same.

So for every combination i would have to loop through these 80k terms to figure out how the tree looks like and what id corresponds to the term name.

Isn’t there a better solution i could use? Something that would turn this hierarchy tree

“Parent term -> Child term -> Grandchild term”

Into

“{parent_term_id} -> {child_term_id} -> {grandchild_term_id}

An SQL query maybe? I’m not sure about how it would look like though.

This is what i’m working with right now

add_action('init', function(){
    
    $parent = get_term_by('name', 'BENELLI', 'fitment');
    $children = get_terms(['taxonomy' => 'fitment','parent' => $parent->term_id]);
    $child = current(array_filter($children, 
        function($item){ 
            return trim($item->name) == 'TRK 502 ABS' ? true : false;
        }
    ));

    $grandChildren = get_terms(['taxonomy' => 'fitment','parent' => $child->term_id]);
    $grandChild = array_filter($grandChildren,
        function($item){
            return trim($item->name) == '2017' ? true : false;
        }
    );

    var_dump([
        'parent' => $parent,
        'child' => $child,
        'grandchild' => $grandChild
    ]);
    die();
}, 10);

0
drpzxc 1 week 2022-07-31T10:05:42-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse