Introduction
Managing WooCommerce stores with custom inventory systems, automating order synchronization is crucial for efficiency and accuracy.
Using WooCommerce hooks, you can implement real-time order syncing directly within your WordPress environment, without relying on REST APIs or cron jobs. This approach allows you to handle order events programmatically, giving full control over business logic and database operations.
This guide provides a step-by-step, code-first approach for developers to integrate WooCommerce orders with custom inventory systems using hooks.
Step 1: Understand WooCommerce Hooks
Hooks are events in WordPress/WooCommerce that trigger your custom code. For syncing orders, we mainly use:
woocommerce_order_status_completed: fires when an order is complete.
woocommerce_order_status_processing: fires when order is paid but not yet shipped.
Step 2: Create Your Hook Function
Add this simple PHP function in your theme’s functions.php or custom plugin:
add_action(‘woocommerce_order_status_completed’, ‘sync_order_to_inventory’, 10, 1);
function sync_order_to_inventory($order_id) {
$order = wc_get_order($order_id);
foreach ($order->get_items() as $item) {
$product_id = $item->get_product_id();
$quantity = $item->get_quantity();
$customer_name = $order->get_billing_first_name() . ‘ ‘ . $order->get_billing_last_name();
// Insert or update in your PHP inventory database or use custom APIs to connect to your database to update orders
}
}
Step 3: Connect to Your Inventory Database
Use a simple database connection:
$inventory_db = new mysqli(‘localhost’, ‘username’, ‘password’, ‘inventory_db’);
if ($inventory_db->connect_error) {
error_log(‘DB connection failed: ‘ . $inventory_db->connect_error);
}
Insert or update orders using prepared statements.
Step 4: Insert or Update Orders
A beginner-friendly approach:
$stmt = $inventory_db->prepare(“INSERT INTO orders (orderid, productid, quantity, customername) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE quantity = VALUES(quantity)”);
$stmt->bind_param(‘iiis’, $order_id, $product_id, $quantity, $customer_name);
$stmt->execute();
$stmt->close();
$inventory_db->close();
This ensures new orders are added and existing orders are updated automatically.
Step 5: Test Your Hook
1. Place a test order in WooCommerce.
2. Verify the order appears in your inventory.
3. Test multiple items, different statuses, and cancellations.
4. Check PHP error logs for debugging if needed.
Step 6: Best Practices for Beginners
– Keep your hook function lightweight.
– Use clear variable names for easy understanding.
– Always backup your database before testing.
– Log errors to troubleshoot easily.
– Learn and experiment gradually — don’t overload with complex logic initially.

Conclusion
Using WooCommerce hooks allows beginners to sync orders to a inventory system efficiently. With practice, you can customize this further and build more advanced automation for your e-commerce store (WooCommerce).