If you’re looking for a free method to export Shopify products and import them into WooCommerce without relying on plugins, you’re in the right place.
With a simple Python script, you can migrate your Shopify products, including images, descriptions, and attributes, to WooCommerce seamlessly. This method supports both simple and variable products.

Import Shopify Products to WooCommerce without Plugins

Many available tools or plugins for migrating products can be costly or lack flexibility. By using the WooCommerce REST API and Shopify’s built-in JSON export feature, you have full control over the migration process without any additional expenses. Plus, the provided Python script does the heavy lifting for you!

Step 1: Export Your Shopify Products as JSON

Shopify enables product data to be exported in JSON format out of the box. Here’s how you can retrieve it:

Visit Your Shopify Product JSON URL: Access your products JSON file by visiting the following URL:

https://your-shopify-site.com/products.json?limit=1000

Replace your-shopify-site.com with your actual Shopify domain. The limit=1000 ensures you retrieve up to 1000 products at once.

Save the JSON File: After visiting the URL, save the response as a .json file. For example, name it products.json.

Step 2: Set Up WooCommerce REST API Keys

To allow the Python script to interact with your WooCommerce store, you need to generate REST API keys.

  1. Log In to WordPress Dashboard:
    • Navigate to WooCommerce > Settings > Advanced > REST API.
  2. Generate API Keys:
    • Click on Add Key.
    • Give the key a name (e.g., “Shopify Migration Script”).
    • Set Permissions to “Read/Write”.
    • Generate the keys and make a note of your Consumer Key and Consumer Secret.
generate Woocommerce API Key

Step 3: Configure the Python Script

The Python script is used to connect to your WooCommerce store and import the products from the Shopify JSON file.

Show the Python script
# Python Script for Importing Shopify Products into WooCommerce
# Code: Maya from WPCookie

import requests
import json
from woocommerce import API
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

wordpress_url ="https://0000000.com"
consumer__key ="000000000000000"
consumer__secret ="000000000000000"
json_file = '/000/000/products.json'

# WooCommerce API credentials
wcapi = API(
    url=wordpress_url,
    consumer_key=consumer__key,
    consumer_secret=consumer__secret,
    version="wc/v3",
    timeout=30  # Increase the timeout value
)

# Load Shopify JSON data
with open(json_file, 'r') as file:
    shopify_data = json.load(file)

# Function to clean image URL
def clean_image_url(url):
    return url.split('?')[0]

# Function to create attributes for variable products
def create_attributes(product_data):
    attributes = []
    for option in product_data.get("options", []):
        if option.get("values"):
            attributes.append({
                "name": option["name"],
                "visible": True,
                "variation": True,
                "options": option["values"]
            })
    return attributes

# Function to create variations
def create_variations(product_data, parent_weight, parent_image):
    variations = []
    for i, variant in enumerate(product_data["variants"]):
        variation = {
            "regular_price": variant["price"],
            "sku": variant.get("sku", str(variant["id"])),  # Use the exact SKU from the JSON file
            "manage_stock": False,  # Uncheck manage stock
            "in_stock": variant["available"],
            "weight": str(variant.get("grams", parent_weight) / 1000),
            "attributes": []
        }
        # Handle options for attributes
        for j, option_key in enumerate(["option1", "option2", "option3"], start=1):
            if variant.get(option_key):
                variation["attributes"].append({
                    "name": product_data["options"][j - 1]["name"],
                    "option": variant[option_key]
                })
        # Add image if available, fallback to parent image
        if variant.get("featured_image"):
            variation["image"] = {"src": clean_image_url(variant["featured_image"]["src"])}
        elif parent_image:
            variation["image"] = {"src": clean_image_url(parent_image)}

        # Set the first variation as default
        if i == 0:
            variation["default"] = True

        variations.append(variation)
    return variations

# Function to create or update a product in WooCommerce
def create_or_update_product(product_data):
    # Determine if product is simple or variable
    is_variable = len(product_data["variants"]) > 1
    # Parent product details
    parent_weight = product_data["variants"][0].get("grams", 0) / 1000
    parent_image = product_data["images"][0]["src"] if product_data.get("images") else None
    product = {
        "name": product_data["title"],
        "type": "variable" if is_variable else "simple",
        "sku": "" if product_data.get("handle") is None else product_data["variants"][0].get("sku", str(product_data["id"])) if not is_variable else "",  # Set SKU to empty string if handle is None
        "regular_price": product_data["variants"][0]["price"] if not is_variable else "",
        "description": product_data["body_html"],
        "short_description": product_data["body_html"],
        "slug": product_data["handle"] if product_data.get("handle") else product_data["title"].lower().replace(" ", "-"),  # Use title as slug if handle is None
        "images": [{"src": clean_image_url(img["src"])} for img in product_data["images"]],
        "meta_data": [{"key": "_vendor", "value": product_data["vendor"]}],
        "weight": str(parent_weight)
    }

    if is_variable:
        product["attributes"] = create_attributes(product_data)

    # Check if the product already exists
    if product["sku"]:
        response = wcapi.get("products", params={"sku": product["sku"]})
    else:
        response = wcapi.get("products", params={"slug": product["slug"]})
    existing_products = response.json()

    if existing_products:
        product_id = existing_products[0]["id"]
        response = wcapi.put(f"products/{product_id}", product)
    else:
        response = wcapi.post("products", product)

    if response.status_code in [200, 201]:
        product_id = response.json().get("id")
        if is_variable:
            variations = create_variations(product_data, parent_weight, parent_image)
            for variation in variations:
                variation_response = wcapi.post(f"products/{product_id}/variations", variation)
                if variation_response.status_code in [200, 201]:
                    print(f"Variation added successfully. SKU: {variation['sku']}")
                else:
                    print(f"Failed to create variation for product {product_data['title']}: {variation_response.json()}")
        print(f"Product {product_data['title']} created/updated successfully.")
    else:
        print(f"Failed to create/update product {product_data['title']}: {response.json()}")

# Import products
for product_data in shopify_data["products"]:
    create_or_update_product(product_data)

Here’s how to configure it:

Install Dependencies: Before running the script, ensure the required libraries are installed. Run the following command:

    pip install requests woocommerce

    Update Script Variables: Open the Python script and update the following variables:

    • wordpress_url: Your WooCommerce store URL (e.g., https://your-wordpress-site.com).
    • consumer__key: Your WooCommerce REST API Consumer Key.
    • consumer__secret: Your WooCommerce REST API Consumer Secret.
    • json_file: The path to the saved Shopify JSON file (e.g., products.json).

    Example configuration:

    wordpress_url = "https://your-wordpress-site.com"
    consumer__key = "ck_examplekey"
    consumer__secret = "cs_examplekey"
    json_file = "path/to/products.json"

    Step 4: Run the Script

    Once the variables are configured, you can run the script to migrate your products.

    • Run the Script: Open a terminal or command prompt, navigate to the script’s directory, and execute:
    python shopify-to-wordpress.py
    Run a Python script in Windows

    To run a Python script in Windows, you’ll need to have Python installed on your system first. If you haven’t installed it yet, you can download it from the official Python website https://www.python.org/downloads/.

    Once Python is installed, follow these steps to run your Python script:

    1. Open the folder containing the Python script you want to run.
    2. Hold the Shift key on your keyboard and right-click in an empty space within the folder.
    3. Select “Open PowerShell window here” or “Open command window here” from the context menu. This will open a command line interface (CLI) with the current directory set to the folder containing your script.
    4. In the CLI, type the following command to run the Python script:Replace your_script_name.py with the actual name of your Python script file. Make sure your script has the .py extension.
    5. Press Enter to execute the command. The Python script will run, and you should see the output or results of the script in the CLI.

    If you want to run the Python script from any location without navigating to the specific folder, you can use the full path to the script file in the command:

    python C:\path\to\your\script\your_script_name.py

    Replace C:\path\to\your\script\ with the actual path of the folder containing your script file.

    run a Python script on a Mac

    To run a Python script on a Mac, you’ll need to have Python installed. Python 2 is pre-installed on macOS, but it’s recommended to install Python 3 for the latest features and updates. You can download Python 3 from the official Python website: https://www.python.org/downloads/.

    Once Python is installed, follow these steps to run your Python script:

    1. Open the Terminal application. You can do this by going to Applications > Utilities > Terminal or using Spotlight search (Command + Space) to search for “Terminal.”
    2. Navigate to the directory where your Python script is located. You can use the cd command followed by the path of the directory to change the current working directory. For example:
    3. Make sure your Python script has the proper file permission to be executed. You can check this by running:If you don’t see an x in the output under the permissions column, you can add it with the following command:Replace your_script_name.py with the name of your Python script file.
    4. Run your Python script by typing:Replace your_script_name.py with the actual name of your Python script file. Make sure your script has the .py extension.
    5. Press Enter to execute the command. The Python script will run, and you should see the output or results of the script in the Terminal window.

    If you want to run the Python script from any location without navigating to the specific folder, you can use the full path to the script file in the command:Copy

    python3 /path/to/your/script/your_script_name.py

    Replace /path/to/your/script/ with the actual path of the folder containing your script file.

    • Watch the Magic Happen:
      • The script reads product data from the Shopify JSON file.
      • It imports product details (images, descriptions, prices, etc.) to your WooCommerce store via the WooCommerce REST API.
      • Both simple products and variable products (with attributes and variations) are supported.
    • Monitor Output: The script will display the progress, including successful imports and any errors.

    Features of the Script

    • Imports Simple and Variable Products: Whether your products have variations (e.g., size, color) or not, the script handles both types seamlessly.
    • Includes Images and Descriptions: Product images, long descriptions, and attributes are all transferred.
    • Customizable: You can extend or modify the script to include more WooCommerce fields or handle additional Shopify data.
    • Error Logging: The script provides output logs for troubleshooting any failed imports.

    Conclusion

    Migrating products from Shopify to WooCommerce doesn’t have to be complicated or expensive. By exporting your product data as JSON and leveraging WooCommerce’s REST API, you can complete the migration with just a few steps. This method is ideal for store owners who want full control over their migration process without relying on plugins.

    If you’re comfortable with Python, this approach is a powerful and flexible solution to move your Shopify products to WooCommerce effortlessly.

    Share this post
    Maya
    Maya

    Hi, my name is Maya and I’m a WordPress plugin developer. I created this website to share some of the helpful codes that I’ve used in my own projects.
    If you’re looking for a custom plugin for your website, you can contact me by clicking on Hire a developer in the menu. I’d love to hear from you.

    Articles: 57

    Leave a Reply

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