WordPress / 10 MIN READ
Woo Stock Quanities Import
Creating WooCommerce Product Buy Buttons
From the original Fervor library. Examples may use older package versions.
How to Import Stock Numbers into WooCommerce Using the Product Import Export for WooCommerce Add-on
Importing stock numbers (inventory quantities) into WooCommerce might sound tricky, but it’s a breeze when you have the right tools. With the Product Import Export for WooCommerce Add-on, you can easily bulk update stock levels. Let’s walk through the process step-by-step:
Step 1: Prepare Your CSV File
WooCommerce uses CSV (Comma-Separated Values) files for importing data. Think of this as a super-organized Excel sheet.
-
Open Your CSV Editor: You can use software like Excel, Google Sheets, or even a text editor.
-
Create/Update Columns: Your CSV file should have these essential columns for stock updates:
- SKU: (Stock Keeping Unit, unique for each product)
- Stock Quantity: The actual inventory number to update.
- Manage Stock (optional): Set to
yesto enable stock management.
Example:
SKU,Stock Quantity,Manage Stock PROD123,50,yes PROD456,120,yes -
Save the File: Save it in CSV format (File > Save As > Select CSV).
Step 2: Install the Plugin
Ensure you have the Product Import Export for WooCommerce Add-on installed and activated.
- Go to your WordPress Dashboard.
- Navigate to Plugins > Add New.
- Search for the plugin by name.
- Install and activate it.
Step 3: Navigate to the Import Tool
- In the WordPress Dashboard, go to WooCommerce > Products.
- Click on the Import button at the top of the page.
Step 4: Upload Your CSV File
- In the Import interface, click Choose File and upload your prepared CSV file.
- Check the box for Update Existing Products to avoid creating duplicates.
- Click Continue.
Step 5: Map Your Fields
WooCommerce will now show a field mapping screen. This helps the platform understand which CSV columns match WooCommerce’s database.
- For each column:
- SKU → Map to SKU.
- Stock Quantity → Map to Stock Quantity.
- Manage Stock → Map to Manage Stock.
- Once mapping is done, click Run the Import.
Step 6: Verify the Import
- Once the import is complete, go to WooCommerce > Products.
- Check a few products to ensure the stock numbers have updated correctly.
Troubleshooting Tips
- Wrong stock values? Double-check the SKU column in your CSV; it must match existing product SKUs exactly.
- CSV not uploading? Make sure it’s saved as a UTF-8 encoded CSV.
- Fields not mapping? Use WooCommerce’s sample CSV template as a guide (found in the Import tool).
Bonus: Automate Future Stock Updates
If you regularly update inventory:
- Use a third-party automation tool like WP All Import.
- Schedule imports from a URL or FTP server for real-time updates.
With this process, your WooCommerce store will always have the right stock levels. Keep your inventory synced and your customers happy! 😊
Bonus areas (two)
Absolutely! Adding custom functions to your theme’s functions.php file can supercharge WooCommerce’s stock management. Here are some cool and functional tweaks you can implement:
1. Auto-Enable Stock Management for All Products
If you often forget to set “Manage Stock” to yes, this snippet automatically enables it for all products when they’re created or imported:
add_action('save_post_product', function ($post_id) {
if (get_post_type($post_id) !== 'product') {
return;
}
update_post_meta($post_id, '_manage_stock', 'yes'); // Enable stock management
});
How it works:
Every time a product is saved (including during an import), stock management is automatically turned on.
2. Default Low Stock Threshold
Set a global low-stock threshold for all products instead of doing it manually:
add_action('save_post_product', function ($post_id) {
if (get_post_type($post_id) !== 'product') {
return;
}
update_post_meta($post_id, '_low_stock_amount', 5); // Set low stock threshold to 5
});
3. Bulk Update Stock via SKU and CSV
Sometimes you want a custom CSV-driven stock update. Here’s how to process a stock update via a CSV upload programmatically:
function update_stock_from_csv($file_path) {
if (!file_exists($file_path)) {
return 'File not found.';
}
$csv = array_map('str_getcsv', file($file_path));
$header = array_shift($csv); // Get headers
foreach ($csv as $row) {
$data = array_combine($header, $row);
$sku = $data['SKU'];
$stock_quantity = $data['Stock Quantity'];
$product_id = wc_get_product_id_by_sku($sku);
if ($product_id) {
update_post_meta($product_id, '_stock', $stock_quantity);
wc_update_product_stock_status($product_id);
}
}
return 'Stock updated successfully.';
}
How to Use:
Call this function in the admin panel, providing the file path of the CSV file. For example:
update_stock_from_csv('/path-to-your-file/stock_update.csv');
4. Email Notification for Critical Stock Levels
Send yourself an email when stock drops below a critical threshold:
add_action('woocommerce_low_stock', function ($product) {
$threshold = 2; // Set your critical threshold
if ($product->get_stock_quantity() <= $threshold) {
wp_mail(
'your-email@example.com',
'Critical Stock Alert',
'The product "' . $product->get_name() . '" is critically low on stock (' . $product->get_stock_quantity() . ').'
);
}
});
5. Add a Custom Column to the Product Table
Show stock levels in the admin product list for quick viewing:
add_filter('manage_edit-product_columns', function ($columns) {
$columns['stock_quantity'] = __('Stock Quantity', 'your-text-domain');
return $columns;
});
add_action('manage_product_posts_custom_column', function ($column, $post_id) {
if ($column === 'stock_quantity') {
$stock = get_post_meta($post_id, '_stock', true);
echo $stock ? $stock : __('N/A', 'your-text-domain');
}
}, 10, 2);
What it does:
Adds a “Stock Quantity” column to the product list in the WooCommerce admin.
6. Log All Stock Changes
Track all stock changes (manual, import, sales) in a custom log file:
add_action('woocommerce_product_set_stock', function ($product) {
$log = ABSPATH . 'wp-content/uploads/stock-changes.log'; // Log file path
$message = sprintf(
"[%s] Product: %s (ID: %d) Stock updated to: %d\n",
date('Y-m-d H:i:s'),
$product->get_name(),
$product->get_id(),
$product->get_stock_quantity()
);
file_put_contents($log, $message, FILE_APPEND);
});
How it works:
Every stock change is recorded in a stock-changes.log file located in the uploads folder.
7. Auto-Restock on Order Cancellation
If a customer cancels an order, the stock automatically adjusts back:
add_action('woocommerce_order_status_cancelled', function ($order_id) {
$order = wc_get_order($order_id);
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$qty = $item->get_quantity();
wc_update_product_stock($product, $qty, 'increase');
}
});
8. Add a “Restock All” Button
Create a bulk action to restock all products in one go:
add_action('admin_footer', function () {
if ('edit-product' !== get_current_screen()->id) {
return;
}
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('<option>').val('restock_all').text('<?php _e('Restock All', 'your-text-domain'); ?>').appendTo('select[name="action"]');
$('<option>').val('restock_all').text('<?php _e('Restock All', 'your-text-domain'); ?>').appendTo('select[name="action2"]');
});
</script>
<?php
});
add_action('load-edit.php', function () {
if (!isset($_REQUEST['action']) || $_REQUEST['action'] !== 'restock_all') {
return;
}
$products = wc_get_products(['limit' => -1]);
foreach ($products as $product) {
$product->set_stock_quantity(100); // Set default restock quantity
$product->save();
}
wp_redirect($_SERVER['HTTP_REFERER']);
exit;
});
What it does:
Adds a “Restock All” action in the WooCommerce product bulk actions dropdown.
Wrapping Up
These functions.php enhancements can turn WooCommerce into an inventory powerhouse, letting you manage stock with less manual work and more automation. Just remember to back up your site before making changes to functions.php—you don’t want to accidentally bring down your store. Happy coding! 🚀
same but different
Yes, there are several ways you can enhance the import/export process and stock management through your functions.php file in WordPress. This is where you can implement custom functions that automate tasks, improve functionality, or extend WooCommerce features. Let’s explore some cool, practical tweaks you can add to make your stock management even more efficient!
1. Automatically Set “Manage Stock” to Yes for All Products
If you want to ensure that all products imported (or newly created) have stock management enabled, you can add this snippet to your functions.php file:
function set_manage_stock_for_all_products($product_id) {
$product = wc_get_product($product_id);
if ($product) {
$product->set_manage_stock(true);
$product->save();
}
}
add_action('woocommerce_product_import_inserted_product', 'set_manage_stock_for_all_products');
What it does:
- Whenever a product is imported, it automatically enables stock management.
- This is great for keeping everything consistent without needing to manually check the stock management box.
2. Update Stock Quantities for Existing Products
Sometimes you need to update the stock quantity of existing products via import. This function allows you to automatically update stock levels after an import based on the SKU, ensuring no duplication or errors.
function update_product_stock_quantity($product_id, $sku, $new_stock_quantity) {
$product = wc_get_product($product_id);
if ($product->get_sku() === $sku) {
$product->set_stock_quantity($new_stock_quantity);
$product->save();
}
}
add_action('woocommerce_product_import_inserted_product', 'update_product_stock_quantity', 10, 3);
What it does:
- After an import, this script checks the SKU of the product being imported and updates the stock quantity based on your CSV data.
- Helps streamline your imports without messing up stock counts.
3. Automatically Set Stock Status Based on Quantity
If you want to automatically mark products as Out of Stock when stock reaches zero or a certain threshold, you can add this to your functions.php file:
function auto_set_stock_status($product_id) {
$product = wc_get_product($product_id);
$stock_quantity = $product->get_stock_quantity();
if ($stock_quantity <= 0) {
$product->set_stock_status('outofstock');
} elseif ($stock_quantity <= 10) {
$product->set_stock_status('onbackorder'); // or "instock", depending on your preference
}
$product->save();
}
add_action('woocommerce_product_updated', 'auto_set_stock_status');
What it does:
- Automatically sets the product status to Out of Stock if stock is 0.
- Can also set a lower stock threshold to trigger statuses like “On Backorder”.
- This way, you keep customers informed without having to manually change stock statuses after import.
4. Create Custom Meta Fields for Imported Products
If you want to add extra custom information (like a warehouse location or supplier name) with your stock import, you can automatically add meta fields during product import:
function add_custom_meta_to_imported_products($product_id) {
$product = wc_get_product($product_id);
// Example: Add custom meta field for warehouse location
$warehouse_location = 'Main Warehouse'; // You can set this dynamically or use a CSV column value
$product->update_meta_data('_warehouse_location', $warehouse_location);
$product->save();
}
add_action('woocommerce_product_import_inserted_product', 'add_custom_meta_to_imported_products');
What it does:
- Adds a custom meta field (e.g.,
_warehouse_location) to the product when it’s imported or updated. - You can expand this to add as many custom fields as you need, such as stock expiration dates, supplier names, etc.
5. Automatically Recalculate Stock After Sale
If you’re selling physical products and want to ensure that stock counts automatically adjust after each sale, you can hook into the WooCommerce order system:
function update_stock_after_sale($order_id) {
$order = wc_get_order($order_id);
foreach ($order->get_items() as $item) {
$product_id = $item->get_product_id();
$product = wc_get_product($product_id);
// Reduce stock quantity based on the number of items sold
$product->reduce_stock($item->get_quantity());
$product->save();
}
}
add_action('woocommerce_order_status_completed', 'update_stock_after_sale');
What it does:
- Each time an order is marked as completed, it automatically reduces the stock quantity of the purchased products.
- You can adjust this to fit your needs (e.g., adjust only for certain product types or categories).
6. Force Product Import to Skip Empty Stock Values
If your CSV file sometimes contains empty stock values (perhaps you’re just updating other attributes), you can force the import to ignore empty stock values and leave them as is:
function skip_empty_stock_import($product_data, $handle) {
if (empty($product_data['stock_quantity'])) {
// Skip or retain current stock quantity if the new import value is empty
$product_data['stock_quantity'] = wc_get_product($product_data['ID'])->get_stock_quantity();
}
return $product_data;
}
add_filter('woocommerce_product_importer_data', 'skip_empty_stock_import', 10, 2);
What it does:
- If a stock quantity is missing or empty in the import file, it keeps the existing stock quantity.
- This avoids overwriting stock values with blanks when doing partial imports.
7. Trigger Stock Alert Based on Custom Threshold
Sometimes, you want to receive notifications or trigger alerts when a product goes below a specific stock threshold. You can create a custom function for this:
function stock_threshold_alert() {
$products = wc_get_products(array(
'status' => 'publish',
'limit' => -1,
));
foreach ($products as $product) {
$stock_quantity = $product->get_stock_quantity();
// Set your low stock threshold (e.g., 10)
if ($stock_quantity <= 10 && $product->get_manage_stock()) {
// Send custom email or alert
wp_mail('youremail@example.com', 'Low Stock Alert', 'Product ' . $product->get_name() . ' is below the threshold.');
}
}
}
// Set a daily check for low stock (you can adjust the frequency as needed)
if (!wp_next_scheduled('stock_threshold_alert_cron')) {
wp_schedule_event(time(), 'daily', 'stock_threshold_alert_cron');
}
add_action('stock_threshold_alert_cron', 'stock_threshold_alert');
What it does:
- Checks stock levels across all products.
- Sends an email alert if a product’s stock goes below your set threshold (10 in this case).
Wrapping It Up
By adding these custom functions in your functions.php file, you can supercharge your WooCommerce inventory management and make your stock imports more efficient. These functions allow you to automate processes, reduce manual errors, and even set up custom alerts. Just remember to back up your functions.php file before making any changes to avoid accidental errors!
Let me know if you need any further tweaks or additional features for your store! 😊