wp-content-exporter
v0.1.1
Published
Export WordPress CMS data to CSV (Framer-friendly)
Maintainers
Readme
wp-content-exporter
Export WordPress CMS data to CSV format, perfect for headless CMS setups and Framer integration.
Automatically handles WordPress REST API pagination, supports multiple authentication methods, and flattens nested JSON fields to create clean, spreadsheet-friendly CSV output.
Features
- 📦 Simple API - One function call to export WordPress content
- 🔐 Multiple Auth Methods - Basic auth, Bearer tokens, or custom headers
- 📄 Nested Field Support - Flatten ACF fields and nested objects using dot notation
- 🔄 Auto Pagination - Automatically handles WordPress REST API pagination
- 📊 CSV Export - Clean CSV generation with json2csv
- 🎯 TypeScript - Full type safety with strict TypeScript support
- 🚀 ESM - Native ES modules support (Node 18+)
Installation
npm install wp-content-exporterQuick Start
Get CSV as String
import { exportToCSV } from "wp-content-exporter"
const csv = await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: ["title.rendered", "slug", "date"]
})
console.log(csv)Save Directly to File
import { exportToCSV } from "wp-content-exporter"
await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: ["title.rendered", "slug", "date"],
outputFile: "./posts.csv" // ← Saves automatically
})
console.log("✓ Saved to posts.csv")Usage
Basic Export (No Authentication)
import { exportToCSV } from "wp-content-exporter"
const csv = await exportToCSV({
endpoint: "https://example.wordpress.com",
postType: "posts",
fields: ["title.rendered", "slug"]
})
console.log(csv)Save to File (Recommended for Large Exports)
// Simply add outputFile option
await exportToCSV({
endpoint: "https://example.wordpress.com",
postType: "posts",
fields: ["title.rendered", "slug"],
outputFile: "./posts.csv" // ← CSV saves directly
})With Basic Authentication
const csv = await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: ["title.rendered", "content.rendered"],
auth: {
type: "basic",
username: "admin",
password: "application-password" // Use app password, not your login password
}
})With Bearer Token
const csv = await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: ["title.rendered", "slug"],
auth: {
type: "bearer",
token: "your-jwt-token-here"
}
})With Custom Headers
const csv = await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: ["title.rendered", "slug"],
auth: {
type: "headers",
headers: {
"Authorization": "Bearer xyz",
"X-Custom-Header": "value"
}
}
})Nested Fields and ACF
const csv = await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: [
"title.rendered",
"acf.price",
"acf.product.name",
"meta.custom_field",
"author"
]
})Pagination Control
const csv = await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: ["title.rendered", "slug"],
perPage: 50 // Default is 100, max 100
})Custom Post Types
const csv = await exportToCSV({
endpoint: "https://example.com",
postType: "custom-post-type", // or "pages"
fields: ["title.rendered", "slug"]
})API Reference
exportToCSV(options: ExportOptions): Promise<string>
Main function to export WordPress content to CSV.
Parameters
endpoint (string, required): Your WordPress site URL
- Example:
"https://example.com" - Must be accessible and have WordPress REST API enabled
- Example:
postType (string, required): Type of content to export
- Default types:
"posts","pages" - Custom post types: Use your custom post type slug
- Default types:
fields (string[], required): Fields to include in the CSV
- Supports dot notation for nested fields
- Example:
["title.rendered", "acf.price"]
auth (AuthConfig, optional): Authentication configuration
- Options:
"none"(default),"basic","bearer","headers"
- Options:
perPage (number, optional): Items per API request (default:
100, max:100)outputFile (string, optional): File path to save CSV
- If provided, CSV is written to file and returned
- If omitted, CSV is only returned as string
- Useful for large exports
Returns
Promise<string>: CSV-formatted string with headers and data rows
Throws
Errorif endpoint is invalidErrorif postType is missingErrorif no fields providedErrorif API request failsErrorif authentication fails
AuthConfig Type
type AuthConfig =
| { type: "none" }
| { type: "basic"; username: string; password: string }
| { type: "bearer"; token: string }
| { type: "headers"; headers: Record<string, string> }Authentication Guide
No Authentication
For public WordPress sites without private content:
// No auth needed, just omit the `auth` parameter
const csv = await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: ["title.rendered", "slug"]
})Basic Auth (Username + Application Password)
- Generate an Application Password in WordPress:
- Go to Users → Your Profile → Application Passwords
- Create a new password (WordPress 5.6+)
- Use it in your code:
const csv = await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: ["title.rendered"],
auth: {
type: "basic",
username: "your-username",
password: "xxxx xxxx xxxx xxxx" // Your app password
}
})Bearer Token (JWT)
For sites using JWT authentication plugins:
const csv = await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: ["title.rendered"],
auth: {
type: "bearer",
token: "eyJhbGciOiJIUzI1NiIs..."
}
})Custom Headers
For custom authentication schemes:
const csv = await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: ["title.rendered"],
auth: {
type: "headers",
headers: {
"X-API-Key": "your-api-key",
"Authorization": "Custom your-custom-auth"
}
}
})Examples
Export Posts to File
import { exportToCSV } from "wp-content-exporter"
async function exportPosts() {
// Simple: just specify outputFile
await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: [
"id",
"title.rendered",
"slug",
"date",
"excerpt.rendered"
],
outputFile: "./posts.csv"
})
console.log("✓ Exported to posts.csv")
}
exportPosts().catch(console.error)Export with Error Handling
async function exportSafely() {
try {
const csv = await exportToCSV({
endpoint: "https://example.com",
postType: "posts",
fields: ["title.rendered", "slug"],
auth: {
type: "basic",
username: "admin",
password: process.env.WP_PASSWORD
},
outputFile: "./posts.csv"
})
const rowCount = csv.split('\n').length - 1
console.log(`✓ Exported ${rowCount} rows to posts.csv`)
} catch (error) {
console.error("❌ Export failed:", error instanceof Error ? error.message : error)
process.exit(1)
}
}Batch Export Multiple Post Types
async function exportAll() {
const postTypes = ["posts", "pages", "products"]
for (const postType of postTypes) {
await exportToCSV({
endpoint: "https://example.com",
postType,
fields: ["title.rendered", "slug", "date"],
outputFile: `./${postType}.csv`
})
console.log(`✓ Exported ${postType}`)
}
}Common Field Names
Standard WordPress Fields
id- Post IDtitle.rendered- Post titlecontent.rendered- Post contentexcerpt.rendered- Post excerptslug- URL slugdate- Publication datestatus- Post status (publish, draft, etc)author- Author IDfeatured_media- Featured image ID
ACF Fields
acf.{field_name}- Simple ACF fieldsacf.{group}.{field}- Grouped ACF fieldsmeta.{field_name}- Custom meta fields
Requirements
- Node.js: 18.0.0 or higher
- npm: 9.0.0 or higher (or yarn/pnpm equivalents)
TypeScript Support
This package includes full TypeScript definitions. Type checking is strict by default:
import { exportToCSV, AuthConfig } from "wp-content-exporter"
// Type-safe configuration
const options: ExportOptions = {
endpoint: "https://example.com",
postType: "posts",
fields: ["title.rendered"],
auth: {
type: "basic",
username: "admin",
password: "password"
}
}
const csv: string = await exportToCSV(options)Performance Tips
Pagination: Large exports use pagination automatically. Adjust
perPagefor optimal speed:// For large datasets perPage: 100 // Maximum allowed by WordPressField Selection: Only export fields you need:
// ✓ Good - minimal fields fields: ["title.rendered", "slug"] // ✗ Bad - includes unnecessary data fields: ["title", "content", "excerpt", "author", "meta", "acf"]Batch Exports: For multiple post types, call sequentially:
const posts = await exportToCSV({ /* posts */ }) const pages = await exportToCSV({ /* pages */ })
Error Handling
The package throws descriptive errors:
try {
const csv = await exportToCSV({
endpoint: "invalid-url",
postType: "posts",
fields: ["title"]
})
} catch (error) {
if (error instanceof Error) {
console.error(error.message)
// "Failed to fetch from invalid-url/wp-json/wp/v2/posts: ..."
}
}Common errors:
- "Endpoint is required" - Missing endpoint URL
- "WordPress REST API error: 401" - Authentication failed
- "WordPress REST API error: 403" - Access denied
- "WordPress REST API error: 404" - Post type not found
- "Failed to fetch" - Network or endpoint unavailable
Development
Setup
git clone https://github.com/gayathri1462/wp-content-exporter.git
cd wp-content-exporter
npm installBuild
npm run buildType Check
npm run type-checkRun Tests
npm testRun Dev Mode
npm run devPublishing
This package uses Changesets for version management and publishing.
Create a Changeset
npm run changesetThis will prompt you to:
- Select the package
- Choose version bump type (patch, minor, major)
- Add a description of changes
The changeset is saved in .changeset/ folder.
Version Update
npm run versionThis:
- Updates
package.jsonversion - Updates
CHANGELOG.md - Creates git tags
Publish to npm
npm run publish-packageOr manually:
npm publishFull Publish Workflow
# 1. Make changes and commit
git add .
git commit -m "feat: add new feature"
# 2. Create changeset
npm run changeset
# 3. Update version and changelog
npm run version
# 4. Publish to npm
npm run publish-package
# 5. Push to GitHub
git push origin main --tagsLicense
MIT
Contributing
Contributions welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
Support
Changelog
See CHANGELOG.md for version history and changes.
