Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon WooCommerce import Tags custom code


WooCommerce import Tags custom code


To import custom product tags in WooCommerce using custom code, you can follow these steps:

1. Create a custom taxonomy for the tags in your theme's functions.php file or a custom plugin:

php
function create_custom_taxonomy() {
    register_taxonomy(
        'product_tags',
        'product',
        array(
            'label' => __( 'Product Tags' ),
            'rewrite' => array( 'slug' => 'product-tags' ),
            'hierarchical' => false,
        )
    );
}
add_action( 'init', 'create_custom_taxonomy' );

This creates a custom taxonomy called "Product Tags" that can be assigned to products[1].

2. Extend the WooCommerce product import functionality to support the custom taxonomy:

php
function woocommerce_add_custom_taxonomy( $product, $data ) {
    $tags = explode( ',', $data['product_tags'] );
    $tags = array_map( 'trim', $tags );
    wp_set_object_terms( $product->get_id(), $tags, 'product_tags' );
    return $product;
}
add_filter( 'woocommerce_product_import_inserted_product_object', 'woocommerce_add_custom_taxonomy', 10, 2 );

This code splits the CSV column "product_tags" by commas, trims the tags, and assigns them to the product using the custom taxonomy[1].

3. In your CSV file, include a column for the custom tags, for example:


ID,Name,product_tags
1,Product 1,"tag1, tag2, tag3"
2,Product 2,"tag2, tag4"

4. Import the CSV file using the WooCommerce product importer. The custom tags will be assigned to the products[1].

5. To display the custom tags on the single product page, you can use the `the_terms()` function:

php
<?php 
$product_tags = get_the_terms( $product->get_id(), 'product_tags' );
if ( $product_tags ) {
    echo '<div class="product-tags">';
    echo '<h3>Product Tags:</h3>';
    echo '<ul>';
    foreach ( $product_tags as $tag ) {
        echo '<li>' . esc_html( $tag->name ) . '</li>';
    }
    echo '</ul>';
    echo '</div>';
}
?>

This code retrieves the custom tags assigned to the product and displays them in an unordered list[4].

By following these steps, you can import custom product tags to WooCommerce using a CSV file and custom code. The key is extending the product importer to support the custom taxonomy and including the tags in the CSV file.

Citations:
[1] https://woocommerce.com/document/product-csv-importer-exporter/
[2] https://www.wpallimport.com/documentation/how-to-import-wordpress-categories-and-tags/
[3] https://www.webtoffee.com/import-product-tags-using-product-import-export/
[4] https://katharinabrunner.de/2020/11/import-custom-taxonomy-to-woocommerce-by-csv-file/
[5] https://woocommerce.com/document/product-csv-import-suite/product-csv-import-suite-importing-products/