# WordPress Integration: Publish to WordPress & WooCommerce (`aimen_ch/wordpress-integration`) Actor

Two-way WordPress integration: publish any Apify actor's dataset as WordPress posts, pages, custom post types or WooCommerce products (with dedupe and safe re-runs), or export WordPress and WooCommerce content as a dataset for other actors.

- **URL**: https://apify.com/aimen_ch/wordpress-integration.md
- **Developed by:** [Aimen Chenomi](https://apify.com/aimen_ch) (community)
- **Categories:** Integrations, Automation, E-commerce
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## WordPress Integration: publish actor results to WordPress & WooCommerce

Connect any WordPress site to Apify, in both directions:

- **Import**: turn the results of *any* Apify actor (a scraper's dataset, a run, or JSON you paste) into WordPress **posts, pages, custom post types or WooCommerce products**. Re-runs update what changed and skip the rest, so nothing gets published twice.
- **Export**: read WordPress and WooCommerce content (posts, pages, custom post types, categories, tags, media, comments, users, products, orders, customers) into a clean dataset that you can download or feed into other actors. Scheduled runs can export only what changed since the last run.

You don't need a WordPress plugin. The actor uses the REST API built into WordPress.

### Quick start (3 minutes)

#### 1. Create an application password

In wp-admin go to **Users → Profile → Application Passwords**, type a name (e.g. "Apify") and click **Add New Application Password**. Copy the password it shows; this is not your login password. Application passwords need WordPress 5.6+ and an HTTPS site.

#### 2. Test the connection (costs only the run start)

Enter the **site URL**, **username** and **application password**, keep **What do you want to do? = Test connection**, and click **Start**. You get a checklist:

```
Site:        My Shop (https://shop.example)
REST API:    OK
Login:       OK, logged in as "apify" (editor)
Permissions: create posts yes, publish yes, pages yes, upload images yes, create categories yes, products NO
WooCommerce: installed, access OK
Post types:  Posts (posts), Pages (pages), Products (product), Portfolio (portfolio)
```

If you also pick some data (a dataset ID, or paste a few items), the check previews how the first row would be published, and says which of your fields go where:

```
title         ← productName         "Walnut Shelf"
content       ← productDescription  "<p>Wall shelf</p>"
featuredImage ← thumbnailImage      "https://…/shelf.jpg"
unique key    ← productUrl          "https://shop.example/shelf"
Not used from your data: listPrice, rating
```

#### 3a. Publish another actor's results automatically

1. Open the actor whose results you want to publish (e.g. a product scraper) → **Integrations** → **Connect actor or task** → choose **WordPress Integration**.
2. Choose **Publish data to WordPress**, fill in the site and login, and pick **Create as** (blog post, page, WooCommerce product or custom post type).
3. Every finished run of that actor is now published to your site. New items start as **drafts**; the run's status message links to them so you can review. Each result row has an **Edit in WordPress** link.

You can also run it by hand with a **Dataset ID**, an **Actor run ID**, or pasted items. Turn on **Dry run** first to see exactly what would be sent; no items are charged.

#### 3b. Export your site

Choose **Export WordPress content** and what to export. Public posts, pages, terms, media and authors need no login; drafts, WooCommerce orders and customers do. Turn on **Only what changed since the last run** for scheduled exports.

### Field mapping

Each WordPress field is filled from a *template*. If you leave the mapping empty, common field names are used: `title`/`name`, `description`/`content`, `image`/`imageUrl`/`images`, `price`, `category`, `tags`.

```json
{
  "title": "{{title || name}}",
  "content": "<p>{{description}}</p>{{specs | table}}<p><a href=\"{{url}}\">Source</a></p>",
  "excerpt": "{{description | stripHtml | truncate:160}}",
  "categories": "{{category}}",
  "tags": "{{tags}}",
  "featuredImage": "{{images.0}}",
  "meta": { "source_url": "{{url}}", "price": "{{price | number}}" }
}
```

| Syntax | Meaning |
|---|---|
| `{{field}}`, `{{a.b}}`, `{{images.0}}`, `{{images.url}}` | value at a path; `images.url` collects `url` from every item of a list |
| `{{a \|\| b \|\| 'fallback'}}` | first value that is not empty |
| `{{price \| money}}` | filters, applied left to right |

**Filters:** `default:x`, `join:", "`, `split:","`, `first`, `last`, `number`, `int`, `money:2`, `multiply:1.2`, `string`, `trim`, `lower`, `upper`, `truncate:160`, `stripHtml`, `escape`, `nl2br`, `json`, `slugify`, `prepend:x`, `append:x`, `replace:from:to`, `date`, `bool`, `list` (HTML list), `table` (HTML table of an object).

**Special keys:**

- `categories`, `tags`: names. Missing terms are created.
- `featuredImage`: an image URL. The image is uploaded to the media library once and reused.
- `meta`: custom fields. They must be registered with `show_in_rest` to be saved.
- For WooCommerce: `images` (a list of URLs, which WooCommerce downloads itself), `sku`, `regular_price`, `sale_price`.

Any other key is sent to the REST API unchanged, e.g. `menu_order`, `comment_status`, `stock_quantity`, `manage_stock`. To turn off a default, map it to `""`.

### HTML safety

Scraped data is untrusted. When the actor logs in as an **administrator**, WordPress saves HTML exactly as sent, without its usual filtering. So by default the actor removes anything that can run code in a visitor's browser:

- `<script>`, `<iframe>`, `<object>`, `<embed>`, `<svg>` and `<form>` elements
- `on…=` event handlers
- `javascript:` links and non-image `data:` links
- CSS expressions

Formatting, links, images, tables and lists are kept. Turn on **Allow unsafe HTML** only for data you trust, e.g. when you need video embeds.

Sanitising also applies to custom fields. Even with it on, it is safer to give the actor an **Editor** account than an administrator, because WordPress then applies its own filtering as well.

### Avoiding duplicates

**Unique key** (default `{{url || id || sku}}`, and the SKU for WooCommerce) identifies a row across runs.

- **Posts:** the actor remembers which WordPress ID each key became, in the **state store** (a named key-value store). It also gives new posts a slug ending in a hash of the key, so posts are found again even with a fresh state store.
- **Products:** products are found by their SKU.
- **Re-runs:**
  - Changed rows are **updated**. Their status is kept, so posts you published by hand stay published.
  - Identical rows are **skipped and not charged**.
  - Items deleted in WordPress are created again.
- **Lost answers:** if WordPress saves an item but its answer is lost (a timeout or 502/504 on slow hosting), the actor looks the item up by slug or SKU before sending it again. So you won't get `my-post` and `my-post-2`.
- **Products without a SKU** get a stable one (`apify-…`, derived from the unique key), so they can always be found again.
- **Images** are uploaded once per URL and remembered per site. If you delete a remembered image from the media library, it is uploaded again the next time it's needed.
- **Dry run** shows exactly what would be sent, without writing anything.

### Example setups

**Scraper → WooCommerce products** (attach to the scraper in its Integrations tab):

```json
{ "mode": "import", "siteUrl": "https://shop.example", "username": "apify", "applicationPassword": "xxxx xxxx xxxx xxxx",
  "target": "wc_product", "postStatus": "draft", "uniqueKey": "{{url}}",
  "fieldMapping": { "name": "{{title}}", "regular_price": "{{price | money}}", "sku": "{{sku || id}}", "images": "{{images}}", "categories": "{{breadcrumbs | last}}" } }
```

**Articles → blog posts**, published straight away, with the source linked:

```json
{ "mode": "import", "siteUrl": "https://blog.example", "username": "apify", "applicationPassword": "…", "target": "post", "postStatus": "publish",
  "fieldMapping": { "title": "{{title}}", "content": "{{text | nl2br}}<p>Source: <a href=\"{{url}}\">{{url}}</a></p>", "excerpt": "{{text | truncate:160}}", "tags": "{{keywords}}" } }
```

**Nightly export of changed posts and orders** (schedule this; each run exports only what changed since the last one):

```json
{ "mode": "export", "siteUrl": "https://shop.example", "username": "apify", "applicationPassword": "…",
  "resources": ["posts", "wc_orders"], "status": "any", "incremental": true }
```

**Preview first:** add `"dryRun": true` to any import to see exactly what would be sent; no items are charged.

### Output

- **Import:** one row per source row, with `action` (`created`, `updated`, `unchanged`, `skipped`, `failed`, or `would-create`/`would-update` in a dry run), `wpId`, `link`, `error` and `warnings`. The `OUTPUT` record holds the totals.
- **Export:** one row per item. Every row has `resource`, `id`, `title`, `url`, `status`, `date` and `modified` (UTC), plus fields for its type:

  - posts: `contentHtml`, `contentText`, `excerpt`, `categories`, `tags`, `featuredImageUrl`, `author`, …
  - products: `sku`, `price`, `stockStatus`, `images`, …
  - orders: `total`, `lineItems`, `billing`, …

  Turn on **Include raw API response** to get everything.

### Speed

Each item takes one or two requests to your site, plus one upload per new image. Images are uploaded once and reused on later runs, and unchanged items cost a single check. How fast that goes depends on your host: by default the actor sends **3 requests at a time**, which shared hosting handles comfortably. On fast or managed hosting (WP Engine, Kinsta, a VPS) raise **Parallel requests** to 8–10 for large imports. If you see timeouts or HTTP 503 errors, lower it to 1–2. Re-running is always safe.

### Pricing

Pay per result, platform usage included:

| Event | Price |
|---|---|
| Item published (a post, page, custom post or product created or updated) | $1.99 per 1,000 (Store discounts: $1.89 Bronze, $1.79 Silver, $1.69 Gold) |
| Item exported (one row of exported content) | $0.49 per 1,000 ($0.47 Bronze, $0.44 Silver, $0.42 Gold) |
| Unchanged, skipped and failed items, dry-run previews | free |
| Run start | $0.00125 at the default 512 MB of memory ($0.00125 per GB, minimum one) |

So a Test connection run costs $0.00125, and publishing 1,000 new products costs $1.99 plus the run start. Scheduled re-runs of the same data cost almost nothing, because unchanged items are not charged.

You can cap the cost of a run with the maximum charge setting: the actor stops cleanly when it is reached, and the next run carries on where it stopped.

### Troubleshooting

| Message | Fix |
|---|---|
| *Could not find the WordPress REST API* | Check the URL. A security plugin or the host may be blocking `/wp-json/`. Sites with plain permalinks are detected and supported (`?rest_route=`). |
| *rejected the username or application password* | Use the application password, not your login password, and the same user's login name. |
| *did not log in the user* (`rest_not_logged_in`) | The host strips the `Authorization` header. Add `SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1` to `.htaccess`. |
| HTTP 403 / firewall page | Allow REST API requests in Wordfence, iThemes, Cloudflare or your host's WAF. |
| Shared hosting slow or 503 | Lower **Parallel requests** to 1–2. Transient errors are retried automatically. |

WooCommerce REST API keys only work over HTTPS. On plain-HTTP test sites, use the application password instead.

### Legal

This actor talks to the WordPress site you point it at, through the REST API that is built into WordPress, using credentials you provide. It only reads and writes content on that site, and only what you ask for. You are responsible for having the right to publish the data you import (for example scraped content, product photos and descriptions) and for handling personal data you export (such as WooCommerce customers and orders) in line with GDPR, CCPA and other laws that apply to you.

WordPress and WooCommerce are trademarks of the WordPress Foundation and Automattic Inc. This actor is not affiliated with, endorsed by or sponsored by them.

# Actor input Schema

## `mode` (type: `string`):

<b>Test connection</b> (only the $0.00125 run start is charged): checks the site, your login, permissions and WooCommerce, and previews how your data would be published. Nothing is written.<br><b>Publish data to WordPress</b>: turn a dataset (e.g. another actor's results) into posts, pages, custom posts or WooCommerce products. Re-runs update instead of duplicating.<br><b>Export WordPress content</b>: save posts, pages, products, orders... to this run's dataset.

## `siteUrl` (type: `string`):

Your site's address, e.g. <code>https://example.com</code>. Any page of the site or a wp-admin link works too.

## `username` (type: `string`):

The login name of the account the actor works as. Needed to publish, and to export drafts, orders or customers. Use an <b>Editor</b> account (or <b>Shop manager</b> for WooCommerce).

## `applicationPassword` (type: `string`):

<b>Not your login password.</b> In wp-admin go to <i>Users → Profile → Application Passwords</i>, type a name like "Apify", click <i>Add New Application Password</i> and paste it here (spaces are fine).

## `datasetId` (type: `string`):

ID (or name) of the dataset to publish, e.g. from the Storage tab of another actor's run.

## `runId` (type: `string`):

Publish the results (default dataset) of this run.

## `items` (type: `array`):

A JSON array of objects, handy for a quick try, e.g. <code>\[{"title": "Hello", "description": "First post"}]</code>.

## `target` (type: `string`):

What each row of your data becomes.

## `postStatus` (type: `string`):

<b>Draft</b> lets you review before anything goes live. Items that already exist keep their status, so what you published by hand stays published.

## `fieldMapping` (type: `object`):

Only needed when the automatic mapping is not what you want. Keys are WordPress fields, values say where the value comes from: <code>{{field}}</code>, nested <code>{{brand.name}}</code>, first available <code>{{title || name}}</code>, with filters <code>{{price | money}}</code>. Special keys: <code>categories</code>, <code>tags</code> (names, created if missing), <code>featuredImage</code> (image URL), <code>meta</code> (custom fields), <code>images</code> (WooCommerce gallery). All filters are listed in the README.

## `uniqueKey` (type: `string`):

The field that identifies the same item across runs, e.g. <code>{{url}}</code> or <code>{{id}}</code>. Leave empty to use the URL, ID or SKU automatically.

## `onExisting` (type: `string`):

Update it with the new data, or leave it as it is in WordPress.

## `dryRun` (type: `boolean`):

Show what would be created or updated, with the exact data sent, without changing your site. Items are not charged; only the run start is.

## `customPostType` (type: `string`):

Only for <i>Create as: Custom post type</i>. Its REST name, e.g. <code>portfolio</code> or <code>job_listing</code>. <b>Test connection</b> lists the ones available on your site.

## `authorId` (type: `integer`):

WordPress user ID shown as the author of new posts. Empty: the account above.

## `usePresetMapping` (type: `boolean`):

Fill WordPress fields you did not map from common field names. In the field mapping, set a field to <code>""</code> to keep it empty.

## `skipUnchanged` (type: `boolean`):

Items whose data did not change since the last run are not touched and not charged.

## `allowUnsafeHtml` (type: `boolean`):

Off (recommended): scripts, iframes, <code>onclick</code>-style attributes and <code>javascript:</code> links are removed from your data, because scraped HTML could otherwise run code on your site. Formatting, links, images and tables are kept. Turn on only for data you trust (e.g. video embeds).

## `offset` (type: `integer`):

Start publishing from this row of the data.

## `resources` (type: `array`):

Pick one or more.

## `incremental` (type: `boolean`):

Great for scheduled runs: each run exports only new and changed items.

## `status` (type: `string`):

Only items with this status, e.g. <code>publish</code>, <code>draft</code>, <code>any</code>, or for orders <code>processing</code>, <code>completed</code>. Several: <code>draft,pending</code>. Values that do not apply to a content type are ignored for it.

## `search` (type: `string`):

Only items matching these words.

## `modifiedAfter` (type: `string`):

Only items created or changed after this date.

## `customResources` (type: `array`):

Also export these custom post types (REST names, e.g. <code>portfolio</code>). <b>Test connection</b> lists them.

## `includeRaw` (type: `boolean`):

Adds every field WordPress returns under <code>raw</code>, for advanced use.

## `wcConsumerKey` (type: `string`):

Starts with <code>ck\_</code>.

## `wcConsumerSecret` (type: `string`):

Starts with <code>cs\_</code>.

## `maxItems` (type: `integer`):

Stop after this many items (per content type when exporting). 0 = no limit. With "Only what changed", the next run continues where this one stopped.

## `maxConcurrency` (type: `integer`):

Requests sent to your site at the same time. Keep 1-3 on shared hosting; raise it for fast, managed hosting.

## `requestTimeoutSecs` (type: `integer`):

How long to wait for your site to answer one request.

## `stateStoreName` (type: `string`):

Name of the key-value store where the actor remembers what it published and exported. Change it only to start over with a fresh memory.

## `payload` (type: `object`):

Filled in automatically when this actor runs from another actor's Integrations tab.

## Actor input object example

```json
{
  "mode": "check",
  "siteUrl": "https://wordpress.org/news",
  "target": "post",
  "postStatus": "draft",
  "fieldMapping": {
    "title": "{{title || name}}",
    "content": "<p>{{description}}</p><p><a href=\"{{url}}\">Source</a></p>",
    "featuredImage": "{{image || imageUrl}}",
    "categories": "{{category}}"
  },
  "onExisting": "update",
  "dryRun": false,
  "usePresetMapping": true,
  "skipUnchanged": true,
  "allowUnsafeHtml": false,
  "offset": 0,
  "resources": [
    "posts"
  ],
  "incremental": false,
  "includeRaw": false,
  "maxItems": 0,
  "maxConcurrency": 3,
  "requestTimeoutSecs": 30,
  "stateStoreName": "wordpress-integration-state"
}
```

# Actor output Schema

## `results` (type: `string`):

No description

## `summary` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "siteUrl": "https://wordpress.org/news",
    "fieldMapping": {
        "title": "{{title || name}}",
        "content": "<p>{{description}}</p><p><a href=\"{{url}}\">Source</a></p>",
        "featuredImage": "{{image || imageUrl}}",
        "categories": "{{category}}"
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("aimen_ch/wordpress-integration").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "siteUrl": "https://wordpress.org/news",
    "fieldMapping": {
        "title": "{{title || name}}",
        "content": "<p>{{description}}</p><p><a href=\"{{url}}\">Source</a></p>",
        "featuredImage": "{{image || imageUrl}}",
        "categories": "{{category}}",
    },
}

# Run the Actor and wait for it to finish
run = client.actor("aimen_ch/wordpress-integration").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "siteUrl": "https://wordpress.org/news",
  "fieldMapping": {
    "title": "{{title || name}}",
    "content": "<p>{{description}}</p><p><a href=\\"{{url}}\\">Source</a></p>",
    "featuredImage": "{{image || imageUrl}}",
    "categories": "{{category}}"
  }
}' |
apify call aimen_ch/wordpress-integration --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,aimen_ch/wordpress-integration"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/6TTJ50Bg6nzbo5WCe/builds/tN3lGMKebGuDoAOvz/openapi.json
