Knowledge Base

Table of Contents

Updated on May 16, 2023

Only Import Existing Woocommerce Categories

Requirement

When importing/migrating products from one Woocommerce website to another we need only import the categories that already exist in the target website.

For example, Website A has “Category X” and “Category Y” and Website B (target website) will only use “Category Y”.

Solution

The category on the target site must be setup first (Category Y) so that it get assigned on the import. Add this code to the Functions Editor on the Import file in WP All Import on target site.

“Here we use the pmxi_single_category filter to prevent WP All Import from creating new taxonomy terms. Only existing terms will be assigned to records during import. This works for all taxonomies – categories, tags, etc.”

function dont_create_terms( $term_into, $tx_name ) {
    
    // Check if term exists, checking both top-level and child
    // taxonomy terms. 
    $term = empty($term_into['parent']) ? term_exists( $term_into['name'], $tx_name, 0 ) : term_exists( $term_into['name'], $tx_name, $term_into['parent'] );

    // Don't allow WP All Import to create the term if it doesn't
    // already exist.
    if ( empty($term) and !is_wp_error($term) ) { 
        return false;
    }

    // If the term already exists assign it.
    return $term_into;

}

add_filter( 'pmxi_single_category', 'dont_create_terms', 10, 2 );