This PHP class provides a mechanism to sync WooCommerce products with an external CSV file via a REST API endpoint in WordPress. The class is designed to update the stock status, regular price, and sale price of products based on the CSV data.
- REST API Integration: Exposes an API route (
/theme-name/v1/sync
) to trigger the product synchronization. - CSV Processing: Downloads a CSV file from a specified URL, parses it, and updates WooCommerce products accordingly.
- Stock Status Update: Automatically updates the stock status of products based on the CSV data.
- Price Update: Updates both regular and sale prices of products as per the CSV file.
- Execution Time Logging: Returns the execution time of the synchronization process in the API response.
- Copy the class into your WordPress theme or plugin.
- Replace the placeholder values with your own:
NAMESPACE
: Set this to a unique identifier for your API namespace.secret_key
: Define a secure key to authenticate API requests.external_feed_url
: Set the URL to the external CSV file containing product data.
- Ensure that WooCommerce is installed and active in your WordPress setup.
Once the class is integrated into your theme or plugin, the REST API route /wp-json/theme-name/v1/sync
will be available. You can trigger the synchronization by making a GET request to this endpoint with the following parameter:
secret_key
: The secret key to authenticate the request.
curl -X GET 'https://your-site.com/wp-json/theme-name/v1/sync?secret_key=my_secret_key'
The CSV file should have the following columns in order:
- SKU: The product's SKU (Stock Keeping Unit).
- Regular Price: The product's regular price.
- Sale Price: The product's sale price (optional).
- Stock Status:
1
for in stock,0
for out of stock.
sku,regular_price,sale_price,status
12345,19.99,14.99,1
67890,29.99,,0
The API returns a JSON response containing the number of updated products and the time taken to complete the process:
{
"new_in_stock": 2,
"new_out_of_stock": 0,
"regular_price": 2,
"sale_price": 1,
"execution_time_seconds": 1.2345
}
Ensure that the WP_Filesystem
API has the necessary permissions to download and manipulate files on your server.
The class handles downloading, reading, and deleting the CSV file during the process.
This project is open-source and available under the MIT License.