WP term_exists和wp_insert_term问题

Maybe I'm trying to reinvent the wheel, but my issue is that I need to check do custom taxonomy term exists, if not than insert this term and afterwards grab term_taxonomy_id of inserted term and assign it to variable. This variable is later used to assign terms for post which will be inserted programmatically. I need to complete all these tasks in one function, because all this is run through wp_cron. At the moment I have tried to run this script from functions.php and from plugin as well – result is the same terms are added, but too late to grab term_taxonomy_id. If I run this function when terms are already in database than of course everything works...

for ( $i = 0; $i < $count; $i++ ) {
    if ( empty( term_exists( $fast_new_categories[ $i ], 'fast-news-categories' ) ) ) {
        $x = $fast_new_categories[ $i ];
        add_action(
            'init',
            function () use ( &$x ) {
                wp_insert_term( $x, 'fast-news-categories', array( 'parent' => 0 ) );
            }
        );
    }
    $fast_news_term[] = term_exists( $fast_new_categories[ $i ], 'fast-news-categories', 0 );
}

My wp_cron task sequence is:

  • I collect post data from API;
  • Than I iterate through it, and first thing I’m trying to do is to check for custom taxonomy term data;
  • Than I make array for post; Than I insert posts;
  • Than I assign terms of custom taxonomy for those just inserted posts – here I need this term_taxonomy_id from term check before.

I understand that I can do term_exists() from functions.php but I can not run wp_insert_term() from it directly, that is why I use add_action with init hook which runs much later.

Can somebody help me to resolve this issue?