---
title: "WooCommerce plugin for Herofab product images (PHP) | Herofab"
description: "A small WordPress plugin that starts Herofab jobs from WooCommerce products and adds each finished image to the product gallery via a signed webhook."
url: https://herofab.app/api/guides/woocommerce-product-images
language: en
updated: 2026-11-12
---

# Herofab images in WooCommerce

A single-file WordPress plugin starts a Herofab job from a WooCommerce product's main image and receives Herofab's signed webhook at its own REST route; a background action then downloads the finished image into the media library and adds it to the product gallery. A second recipe does the same from outside WordPress with the REST APIs.

- WordPress plugin, PHP 8
- WooCommerce Action Scheduler
- Signed webhooks

## What you need

1. A Herofab API key with the jobs:read, jobs:write and webhooks:write scopes, and a webhook endpoint for job.succeeded pointing at https://your-store.example/wp-json/herofab/v1/webhook.
2. The key and the whsec\_ secret as constants in wp-config.php, outside the database.
3. herofab\_verify(): the PHP signature check from the Herofab webhooks page, in the same plugin file.
4. Product main images at public URLs, as WooCommerce serves them by default.

## herofab-images.php

The webhook route only checks the signature and queues the work with Action Scheduler, which WooCommerce includes, so Herofab gets its answer within 10 seconds. The image is added to the gallery with the product's own methods, which keep the existing images.

```
<?php
/**
 * Plugin Name: Herofab images for WooCommerce
 * Description: Starts Herofab jobs for products and adds each finished image to the product gallery.
 * Requires Plugins: woocommerce
 */
// In wp-config.php: define('HEROFAB_API_KEY', 'hf_sk_live_…'); define('HEROFAB_WEBHOOK_SECRET', 'whsec_…');
const HEROFAB_API = 'https://app.herofab.app/api/v1';

/** Start a job from the product's main image (a public URL). Run with WP-CLI: wp eval 'herofab_start(123);' */
function herofab_start(int $product_id): void {
    $product = wc_get_product($product_id);
    $headers = ['Authorization' => 'Bearer ' . HEROFAB_API_KEY, 'Content-Type' => 'application/json'];
    $asset = json_decode(wp_remote_retrieve_body(wp_remote_post(HEROFAB_API . '/assets', [
        'headers' => $headers, 'timeout' => 60,
        'body' => wp_json_encode(['url' => wp_get_attachment_url($product->get_image_id())]),
    ])), true);
    $job = json_decode(wp_remote_retrieve_body(wp_remote_post(HEROFAB_API . '/jobs', [
        'headers' => $headers + ['Idempotency-Key' => "woo-$product_id-product_studio"], 'timeout' => 30,
        'body' => wp_json_encode(['tool' => 'product_studio', 'inputs' => ['product' => $asset['id']],
            'params' => ['scene' => 'studio_white', 'shadow' => 'soft']]),
    ])), true);
    $jobs = get_option('herofab_jobs', []);
    $jobs[$job['id']] = $product_id;
    update_option('herofab_jobs', $jobs, false);
}

/** Webhook address: https://your-store.example/wp-json/herofab/v1/webhook */
add_action('rest_api_init', function () {
    register_rest_route('herofab/v1', '/webhook', [
        'methods' => 'POST',
        'permission_callback' => '__return_true',   // the signature check is the authentication
        'callback' => function (WP_REST_Request $request) {
            $headers = [];
            foreach (['webhook-id', 'webhook-timestamp', 'webhook-signature'] as $name) $headers[$name] = (string) $request->get_header($name);
            if (!herofab_verify(HEROFAB_WEBHOOK_SECRET, $headers, $request->get_body())) return new WP_REST_Response(null, 401);
            $event = json_decode($request->get_body(), true);
            if ($event['type'] === 'job.succeeded' && !get_transient('herofab_' . $event['id'])) {
                set_transient('herofab_' . $event['id'], 1, DAY_IN_SECONDS);   // retries reuse the same id
                as_enqueue_async_action('herofab_attach', [$event['data']['job']['id']]);  // answer within 10 s
            }
            return new WP_REST_Response(null, 200);
        },
    ]);
});

add_action('herofab_attach', function (string $job_id) {
    $product_id = get_option('herofab_jobs', [])[$job_id] ?? null;
    if (!$product_id) return;
    $auth = ['headers' => ['Authorization' => 'Bearer ' . HEROFAB_API_KEY], 'timeout' => 30];
    $job = json_decode(wp_remote_retrieve_body(wp_remote_get(HEROFAB_API . "/jobs/$job_id", $auth)), true);
    $output = $job['outputs'][0];
    // The content URL answers with a short-lived link: follow it without the API key.
    $first = wp_remote_get(HEROFAB_API . "/assets/{$output['asset_id']}/content", $auth + ['redirection' => 0]);
    $location = wp_remote_retrieve_header($first, 'location');
    $bytes = wp_remote_retrieve_body($location ? wp_remote_get($location, ['timeout' => 60]) : $first);
    $upload = wp_upload_bits("herofab-$job_id." . explode('/', $output['content_type'])[1], null, $bytes);
    if (!empty($upload['error'])) return;
    $attachment = wp_insert_attachment(['post_mime_type' => $output['content_type'], 'post_title' => 'Herofab', 'post_status' => 'inherit'], $upload['file'], $product_id);
    require_once ABSPATH . 'wp-admin/includes/image.php';
    wp_update_attachment_metadata($attachment, wp_generate_attachment_metadata($attachment, $upload['file']));
    $product = wc_get_product($product_id);
    $product->set_gallery_image_ids([...$product->get_gallery_image_ids(), $attachment]);   // adds, keeps the others
    $product->save();
});

// herofab_verify(): the PHP function on the webhooks page.
```

## The same from outside WordPress

WooCommerce REST keys work only on WooCommerce routes; the media upload needs a WordPress Application Password of a user who may upload files. Send the raw image with Content-Type and Content-Disposition, then add its id to the product's images.

```
# Outside WordPress: upload with an Application Password, then add the image id to the product.
import requests

STORE = "https://your-store.example"
WP_AUTH = ("admin-user", "xxxx xxxx xxxx xxxx xxxx xxxx")      # Users → Profile → Application Passwords
WC_AUTH = ("ck_…", "cs_…")                                    # WooCommerce → Settings → Advanced → REST API

def attach(product_id: int, image: bytes, filename: str, content_type: str) -> None:
    media = requests.post(f"{STORE}/wp-json/wp/v2/media", auth=WP_AUTH, data=image, headers={
        "Content-Type": content_type,
        "Content-Disposition": f'attachment; filename="{filename}"',
    }).json()
    product = requests.get(f"{STORE}/wp-json/wc/v3/products/{product_id}", auth=WC_AUTH).json()
    # images replaces every image of the product: send the existing ones too, the first stays the main image.
    images = [{"id": img["id"]} for img in product["images"]] + [{"id": media["id"]}]
    requests.put(f"{STORE}/wp-json/wc/v3/products/{product_id}", auth=WC_AUTH, json={"images": images}).raise_for_status()
```

## WordPress and WooCommerce facts this recipe relies on

| Item | Documentation |
| --- | --- |
| Product images | Each image is either id (an attachment from the media library) or src (an image URL WooCommerce downloads) |
| Replacing | The images list replaces all product images: the first is the main image, the rest the gallery |
| WooCommerce keys | Consumer key and secret over HTTPS basic auth, for WooCommerce routes only |
| Media upload | POST /wp/v2/media with the raw file needs Content-Type and Content-Disposition (attachment; filename=…) and the upload\_files capability |
| Application Passwords | Built into WordPress since 5.6, created under Users → Profile, sent as HTTPS basic auth |

[WooCommerce REST API — product images](https://woocommerce.github.io/woocommerce-rest-api-docs/#product-images-properties) · [WooCommerce REST API — authentication](https://woocommerce.github.io/woocommerce-rest-api-docs/#authentication-over-https) · [WordPress REST API — media](https://developer.wordpress.org/rest-api/reference/media/) · [WordPress REST API — authentication](https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/) · checked 30 October 2026

## WooCommerce recipe questions

**Why not pass the Herofab download link as src?**

WooCommerce downloads src when the product is saved, and a Herofab download link is short-lived and obtained with your API key. Saving the bytes into the media library first and using the attachment id avoids both problems.

**Will the plugin change my main product image?**

No. It adds the image to the end of the gallery with set\_gallery\_image\_ids; the main image stays until you change it.

**What if the same webhook arrives twice?**

The event id is stored as a transient for a day, and a repeated delivery is acknowledged without queuing a second download.

Related

[Product studio API](https://herofab.app/api/product-photography) · [Webhooks](https://herofab.app/api/webhooks) · [Bulk product photos script](https://herofab.app/api/guides/bulk-product-photos) · [Shopify product images](https://herofab.app/api/guides/shopify-product-images) · [API overview: upload, poll, download](https://herofab.app/api)
