Practical example of automation with WordPress

When you hear the word \”migration\” at the latest, you should stop and think about automation. Migration projects are usually always associated with copying data: An old system is replaced, a new one is started up, but the data must of course be available in the new system.

With millions of data records, it goes without saying that this is not done manually, in my example it was only 150 data records and yet the automation was many times faster (remember: automation is a matter of settings)

The work process was as follows:

  • Product category Open
  • Search for a product from this product category
  • View image URL of the product
  • Copy the name of the image
  • Add the image of the product in the product category

This whole process takes about 30 seconds and is extremely stupid. With 150 categories, this takes 75 minutes and requires a lot of nerves.

Here is my approach:

def update_category_images():
    wcapi = get_woocommerce_object(app)
    page = 1
    more = True
    while more:
        response = wcapi.get(f\'products/categories?per_page=30&page={page}\')
        if response.ok:
            categories = response.json()
            if len(categories) == 0:
                more = False
            for cat in categories:
                result = wcapi.get(\"products?category=\" + str(cat[\"id\"]))
                if result.ok:
                    products = result.json()
                    if len(products) > 0:
                        product = products[0]
                        cat[\'image\'] = product[\"images\"][0]
                        res = wcapi.put(f\"products/categories/{cat[\'id\']}\", cat)
                        if res.ok:
                            print(\"update ok\")
                            print(\"update not ok\")
        page = page + 1
    return \"done\"

Writing this took just 20 minutes and solved the migration. This also gives me a building block (or process) for the future: if for some reason the same task comes up again, I can simply call up the process and sit back and wait.


You can take two lessons from this

  • Always work with a system that has an interface (API)
  • Basic programming skills are priceless!