> ## Documentation Index
> Fetch the complete documentation index at: https://docs.drmanhlinhmd.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Wp import guide

# WordPress Batch Import Guide

Comprehensive guide for the WordPress batch import orchestrator script.

## Overview

The `wp-batch-import.sh` script is a master orchestrator that manages the complete WordPress product import workflow with safety checks, rollback capability, and detailed reporting.

## Features

* **Safety First**: Automatic backups before any changes
* **Interactive Mode**: Step-by-step confirmations
* **Dry-Run Mode**: Test without making actual changes
* **Rollback Capability**: Restore from backups if needed
* **Progress Tracking**: Real-time progress with ETA
* **Detailed Logging**: Console and file logging
* **Email Notifications**: Optional email reports
* **Error Handling**: Comprehensive error handling and recovery

## Prerequisites

* WP-CLI installed
* Node.js and npm
* WordPress installation
* WooCommerce REST API keys
* CSV product file

## Installation

1. **Clone or download scripts** to `/scripts/` directory:

```bash theme={null}
cd /Users/tannguyen/Documents/fullstack/triseo.drmanhlinhmd.com/scripts
chmod +x wp-batch-import.sh
chmod +x wp-import-config.sh
```

2. **Configure environment** in `.env` file:

```bash theme={null}
# WordPress Configuration
WP_PATH="/path/to/wordpress"
WP_USER="admin"
SITE_URL="https://drmanhlinhmd.com"

# WooCommerce API
ck=ck_your_consumer_key
cs=cs_your_consumer_secret

# Import Options
DRY_RUN=false
SKIP_DOWNLOADS=false
VERIFY=true
```

## Quick Start

### Basic Usage

```bash theme={null}
# Interactive mode with confirmations
./scripts/wp-batch-import.sh

# Dry-run mode (test without changes)
./scripts/wp-batch-import.sh --dry-run

# Automated mode (no confirmations)
./scripts/wp-batch-import.sh --non-interactive

# Full automated with email notification
./scripts/wp-batch-import.sh --non-interactive --email
```

### Configuration Helper

```bash theme={null}
# Show current configuration
./scripts/wp-import-config.sh show

# Validate configuration
./scripts/wp-import-config.sh validate

# Interactive setup
./scripts/wp-import-config.sh setup

# Export configuration
./scripts/wp-import-config.sh export > import-config.sh
```

## Workflow Steps

The script executes the following steps in order:

### 1. Pre-check

* Verify WP-CLI installation
* Check WordPress path
* Validate CSV file
* Test database connection
* Check required dependencies

### 2. Backup

* Export WordPress database
* Backup uploads metadata
* Store backup with timestamp
* Save backup location for rollback

### 3. Download Images

* Extract image URLs from CSV
* Download images to temp directory
* Skip existing images
* Track download statistics

### 4. Generate SEO Content

* Analyze product data
* Generate meta descriptions
* Create SEO-friendly titles
* Optimize product descriptions

### 5. Update Products

* Match existing products by SKU
* Update product metadata
* Update prices and stock
* Preserve existing data

### 6. Create Products

* Create new product posts
* Set product categories
* Assign product attributes
* Link product images

### 7. Verify Import

* Count imported products
* Validate product data
* Check for errors
* Generate import report

## Command Line Options

| Option              | Description                       |
| ------------------- | --------------------------------- |
| `--dry-run`         | Run without making actual changes |
| `--skip-downloads`  | Skip image downloads              |
| `--no-verify`       | Skip import verification          |
| `--non-interactive` | Run without confirmations         |
| `--email`           | Send email notification           |
| `--help`            | Show help message                 |

## Environment Variables

| Variable         | Description                 | Default                    |
| ---------------- | --------------------------- | -------------------------- |
| `WP_PATH`        | WordPress installation path | `/path/to/wordpress`       |
| `WP_USER`        | WordPress username          | `admin`                    |
| `SITE_URL`       | Site URL                    | `https://drmanhlinhmd.com` |
| `DRY_RUN`        | Enable dry run mode         | `false`                    |
| `SKIP_DOWNLOADS` | Skip image downloads        | `false`                    |
| `VERIFY`         | Enable verification         | `true`                     |
| `INTERACTIVE`    | Enable confirmations        | `true`                     |
| `EMAIL_NOTIFY`   | Enable email                | `false`                    |
| `EMAIL_TO`       | Email recipient             | `admin@example.com`        |

## Examples

### Test Run (Recommended First Step)

```bash theme={null}
# Load config and do a dry run
source scripts/wp-import-config.sh export
./scripts/wp-batch-import.sh --dry-run
```

### Production Import

```bash theme={null}
# Interactive import with confirmations
./scripts/wp-batch-import.sh

# Automated import
./scripts/wp-batch-import.sh --non-interactive

# Import with email notification
./scripts/wp-batch-import.sh --non-interactive --email
```

### Skip Image Downloads

```bash theme={null}
# If images are already downloaded
./scripts/wp-batch-import.sh --skip-downloads
```

### Custom Configuration

```bash theme={null}
# Set custom WP path
WP_PATH="/var/www/html" ./scripts/wp-batch-import.sh

# Multiple options
SKIP_DOWNLOADS=true VERIFY=false ./scripts/wp-batch-import.sh --non-interactive
```

## Output and Logs

### Console Output

The script provides colored console output:

* 🟢 Green: Success messages
* 🔴 Red: Error messages
* 🟡 Yellow: Warnings
* 🔵 Blue: Information
* 🟣 Purple: Debug messages

### Log Files

Logs are saved to `/logs/` directory:

```bash theme={null}
logs/
├── import-20240110-143022.log      # Main log file
└── import-report-20240110-143520.txt  # Final report
```

### Statistics Report

The final report includes:

* Products processed/updated/created/failed
* Images downloaded/failed
* Total errors
* Execution time
* Backup location

## Rollback

If the import fails or you need to undo changes:

```bash theme={null}
# The script will prompt for rollback on failure
# Or manually rollback from backup:

# Find latest backup
cat backups/latest.txt

# Restore database
wp db import backups/backup-20240110-143022/database.sql --path=/path/to/wp
```

## Troubleshooting

### WP-CLI Not Found

```bash theme={null}
# Install WP-CLI
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp
```

### Permission Denied

```bash theme={null}
# Make scripts executable
chmod +x scripts/wp-batch-import.sh
chmod +x scripts/wp-import-config.sh
```

### Database Connection Error

```bash theme={null}
# Check WordPress config
cat /path/to/wordpress/wp-config.php

# Test WP-CLI
wp core version --path=/path/to/wordpress
```

### Image Download Failures

```bash theme={null}
# Check image URLs in CSV
cat docs/bruno_vassari_wp_products.csv | awk -F',' '{print $NF}'

# Test manual download
curl -I <image_url>
```

### WooCommerce API Errors

```bash theme={null}
# Verify API keys in .env
grep -E "^(ck|cs)=" .env

# Regenerate keys in WordPress admin:
# WooCommerce > Settings > Advanced > REST API
```

## CSV File Format

Expected CSV structure:

```csv theme={null}
sku,name,description,price,stock,category,image_url
BV001,"Product Name","Description",99.99,10,"Category","https://example.com/image.jpg"
```

## Best Practices

1. **Always test with dry-run first**
2. **Keep regular backups**
3. **Monitor logs for errors**
4. **Verify imports in WordPress admin**
5. **Use non-interactive mode for automation**
6. **Enable email notifications for production**
7. **Keep CSV file validated and clean**

## Automation

### Cron Job

```bash theme={null}
# Add to crontab (crontab -e)
0 2 * * * cd /path/to/project && ./scripts/wp-batch-import.sh --non-interactive --email
```

### CI/CD Pipeline

```yaml theme={null}
# Example for GitHub Actions
- name: Run WordPress Import
  run: |
    ./scripts/wp-batch-import.sh --non-interactive
```

## Support

For issues or questions:

* Check log files in `/logs/`
* Review configuration with `wp-import-config.sh validate`
* Test with `--dry-run` first
* Check WordPress and WooCommerce requirements

## License

MIT License - See project root for details.
