Last updated on October 18, 2023

WooCommerce product export/import solutions

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Handle product import/export efficiently in WooCommerce.

One common task when working with WooCommerce is exporting and importing products. This can be useful when migrating your store to a new site, updating product information in bulk, or syncing products with a third-party system.

To achieve this functionality, you can use the built-in WooCommerce product import/export tools or leverage custom code to create more advanced solutions.

Here’s an example of how you can export WooCommerce products using the built-in tools:

function wpsnippets_export_products() {
    // Get all products
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => -1,
    );
    $products = get_posts( $args );

    // Prepare data for export
    $export_data = array();
    foreach ( $products as $product ) {
        $export_data[] = array(
            'ID'           => $product->ID,
            'post_title'   => $product->post_title,
            'post_content' => $product->post_content,
            // Add more fields as needed
        );
    }

    // Generate CSV file
    $csv_file = 'path/to/export.csv';
    $csv_handle = fopen( $csv_file, 'w' );
    if ( $csv_handle ) {
        fputcsv( $csv_handle, array_keys( $export_data[0] ) ); // Write header row
        foreach ( $export_data as $data ) {
            fputcsv( $csv_handle, $data ); // Write data rows
        }
        fclose( $csv_handle );
    }

    // Output download link
    echo '<a href="' . esc_url( $csv_file ) . '">Download Exported Products</a>';
}

This code snippet defines a custom function wpsnippets_export_products() that exports all WooCommerce products to a CSV file. It retrieves the products using get_posts() and prepares the data for export. Then, it generates a CSV file and outputs a download link for the exported file.

To use this code, you can add it to your theme’s functions.php file or create a custom plugin. After adding the code, you can call the wpsnippets_export_products() function wherever you want the export functionality to be triggered.

Remember to update the 'path/to/export.csv' with the desired file path for the export.

This code snippet can be useful when you need to export WooCommerce products for backup purposes, migrating to a new site, or performing bulk updates to product information.

Examples

Example 1: Export WooCommerce Products to CSV

This example demonstrates how to export WooCommerce products to a CSV file using the built-in WordPress functions.

function wpsnippets_export_products_to_csv() {
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => -1,
    );

    $products = get_posts( $args );

    if ( ! empty( $products ) ) {
        $csv_data = array( 'Product ID', 'Product Name', 'Price' );

        foreach ( $products as $product ) {
            $product_data = array(
                $product->ID,
                $product->post_title,
                get_post_meta( $product->ID, '_regular_price', true ),
            );

            $csv_data[] = implode( ',', $product_data );
        }

        $csv_file = implode( "n", $csv_data );

        header( 'Content-Type: text/csv' );
        header( 'Content-Disposition: attachment; filename=woocommerce_products.csv' );

        echo $csv_file;
        exit;
    }
}

This code exports all WooCommerce products to a CSV file. It retrieves the products using get_posts() function, iterates through each product, and retrieves the necessary data such as ID, name, and price. The data is then formatted as CSV and outputted as a downloadable file.

Example 2: Import WooCommerce Products from CSV

This example demonstrates how to import WooCommerce products from a CSV file using custom PHP functions.

function wpsnippets_import_products_from_csv() {
    if ( isset( $_FILES['csv_file'] ) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK ) {
        $csv_file = $_FILES['csv_file']['tmp_name'];

        if ( ( $handle = fopen( $csv_file, 'r' ) ) !== false ) {
            while ( ( $data = fgetcsv( $handle, 1000, ',' ) ) !== false ) {
                $product_data = array(
                    'post_title'     => $data[1],
                    'post_type'      => 'product',
                    'post_status'    => 'publish',
                    'meta_input'     => array(
                        '_regular_price' => $data[2],
                    ),
                );

                $product_id = wp_insert_post( $product_data );

                if ( ! is_wp_error( $product_id ) ) {
                    update_post_meta( $product_id, '_price', $data[2] );
                }
            }

            fclose( $handle );
        }
    }
}

This code imports WooCommerce products from a CSV file. It reads the CSV file using fgetcsv() function, retrieves the necessary data such as title and price, and creates a new product using wp_insert_post() function. The product’s regular price is also set using update_post_meta() function.

Example 3: Synchronize WooCommerce Products with External System

This example demonstrates how to synchronize WooCommerce products with an external system using custom PHP functions.

function wpsnippets_synchronize_products() {
    $external_products = get_external_products(); // Function to retrieve products from external system

    if ( ! empty( $external_products ) ) {
        foreach ( $external_products as $external_product ) {
            $product_id = wpsnippets_get_product_id_by_external_id( $external_product['id'] );

            if ( $product_id ) {
                // Update existing product
                $product_data = array(
                    'ID'             => $product_id,
                    'post_title'     => $external_product['name'],
                    'meta_input'     => array(
                        '_regular_price' => $external_product['price'],
                    ),
                );

                wp_update_post( $product_data );
                update_post_meta( $product_id, '_price', $external_product['price'] );
            } else {
                // Create new product
                $product_data = array(
                    'post_title'     => $external_product['name'],
                    'post_type'      => 'product',
                    'post_status'    => 'publish',
                    'meta_input'     => array(
                        '_regular_price' => $external_product['price'],
                    ),
                );

                $product_id = wp_insert_post( $product_data );

                if ( ! is_wp_error( $product_id ) ) {
                    update_post_meta( $product_id, '_price', $external_product['price'] );
                }
            }
        }
    }
}

This code synchronizes WooCommerce products with an external system. It retrieves the products from the external system, iterates through each product, and checks if it already exists in WooCommerce. If the product exists, it updates the existing product’s title and regular price using wp_update_post() function. If the product doesn’t exist, it creates a new product using wp_insert_post() function. The product’s price is also set using update_post_meta() function.

Last updated on October 18, 2023. Originally posted on January 7, 2024.

Leave a Reply

Your email address will not be published. Required fields are marked *