Migrate Post Categories to Portfolio Category with Parent-Child Structure

Description


// Copy 'category' terms to 'portfolio_category' preserving parent-child structure
function migrate_post_categories_with_hierarchy() {
    $post_categories = get_categories(array(
        'taxonomy' => 'category',
        'hide_empty' => false,
        'orderby' => 'term_id',
        'order' => 'ASC',
    ));

    $term_map = array(); // Old term_id => New term_id

    foreach ($post_categories as $cat) {
        $parent_id = 0;

        // If has parent, check mapped new ID
        if ($cat->parent && isset($term_map[$cat->parent])) {
            $parent_id = $term_map[$cat->parent];
        }

        // Insert into portfolio_category
        $result = wp_insert_term(
            $cat->name,
            'portfolio_category',
            array(
                'slug' => $cat->slug,
                'description' => $cat->description,
                'parent' => $parent_id,
            )
        );

        if (!is_wp_error($result) && isset($result['term_id'])) {
            $term_map[$cat->term_id] = $result['term_id'];
        }
    }

    echo "Portfolio categories created with hierarchy.";
}
add_action('init', 'run_portfolio_category_hierarchy_migration_once');

function run_portfolio_category_hierarchy_migration_once() {
    if (get_option('portfolio_category_tree_migrated')) return;

    migrate_post_categories_with_hierarchy();
    update_option('portfolio_category_tree_migrated', true); // Run only once
}

What I have done here?

  • Written the php code in such way so that it run once in first time. never run again.

Technology Used