How to fill in costs for 500 products without 500 clicks
Typing 500 costs one product at a time is enough to put anyone off the feature. You do not have to: WooCommerce's own product CSV import fills the cost field in bulk, and a short WP-CLI script does the same with a dry run first.
Updated
This page assumes the Cost of Goods Sold feature is already switched on. If it is not, the guide to enabling it is shorter than this page and comes first: while the switch is off, the costs you enter never reach a single order.
First work out how many products you actually need
The instinct is to fill in everything. That is the most expensive possible order, because the first eighty percent of the value goes in during the first hour and the rest takes the rest of the week.
A profit report does not need a complete catalog. It needs coverage—what share of revenue has a known cost behind it. A store that knows the cost of the fifty products making 80% of sales has a usable report; a store that knows the cost of four hundred long-tail products and not of its ten bestsellers has nothing.
So there is only one sensible order: sort the catalog by revenue and work down, not alphabetically and not by date added. Stop when coverage stops rising fast enough to justify the typing.
Filling in costs does not change orders already in the database. Cost is written onto the order line at the moment of sale, so what you enter today works from today forward. That is not a reason to wait—it is a reason to do it this week rather than next quarter.
Decide once what “cost” means
Do this before the first row. Purchase price alone? Including inbound shipping? Duty, packaging, platform fees? Every one of those answers is valid, and none of them is valid for half the catalog. A margin computed from two different definitions of cost is not comparable to anything, including itself a month ago. Write the choice down somewhere outside the file you import, so you are not guessing in six months.
The quickest route: WooCommerce’s product import
WooCommerce’s own product CSV importer fills the cost field, and you need no code for it. With the feature on, the product export has a Cost of goods column, and the import reads it back.
- Go to Products → All Products and click Export. Under Which columns should be exported?, pick ID, SKU, Name, and Cost of goods, then click Generate CSV.
- In your spreadsheet, fill in the Cost of goods column: the net cost of one item, a number with no currency symbol. Leave the header row as it is.
- Go back to Products → All Products, click Import, choose your file, check Update existing products, and click Continue. On the next screen, check that your Cost of goods column maps to Cost of goods, then click Run the importer.
If your spreadsheet saves the file with semicolons (Excel does that in many European countries), open Show advanced options during the import and enter a semicolon as the CSV Delimiter.
Two things to know first. An empty cell in the Cost of goods column sets that product to “no cost”, so do not clear a cost you want to keep; delete the row instead. And the import does not show you what it is about to change. If you want to see every change before it happens, use the script below.
For the script: a spreadsheet with three columns
Download the CSV template or build your own; the layout is what matters:
id,sku,cost
1042,,41.50
,TSHIRT-XL-BLACK,24.00
1198,,
idorsku—one of the two, not both. The script takesid, and when it is empty it looks the product up bysku.cost—net cost for a single unit, with no currency symbol and no spaces. “41.50” and “41,50” both work.- An empty
costmeans “we don’t know”, and the script skips that row. Do not type zero instead: a stored zero and a missing cost are the same thing in the WooCommerce database, so a zero typed “for now” adds nothing and clears any cost the product already had.
In many European countries, Excel saves CSV files with semicolons between the columns instead of commas. The script detects this from the header row, so you can save the file straight from Excel.
Where to get the product list: the export in Products → All Products gives you a CSV with
ID and SKU columns. Keep those two, add a cost column, and fill it in where you can see
everything at once.
The script—one pass over the file
The script below runs through WP-CLI. It reads the CSV, finds the product, writes the cost and reports what it did. It starts in dry-run mode—the first line decides.
<?php
/**
* Fills the native Cost of Goods Sold field from a CSV file (id,sku,cost).
* Run with: wp eval-file fill-costs.php costs.csv
*/
$DRY_RUN = true; // <- switch to false only after a successful trial
$file = $args[0] ?? 'costs.csv';
$handle = fopen( $file, 'r' );
if ( ! $handle ) {
WP_CLI::error( "Cannot open file: {$file}" );
}
$header = (string) fgets( $handle ); // header row: id,sku,cost
// Excel in many European countries saves CSV with semicolons, so take the separator from the header.
$sep = substr_count( $header, ';' ) > substr_count( $header, ',' ) ? ';' : ',';
$written = 0;
$skipped = 0;
$failed = 0;
while ( ( $row = fgetcsv( $handle, 0, $sep, '"', '' ) ) !== false ) {
list( $id, $sku, $cost ) = array_pad( $row, 3, '' );
$cost = trim( str_replace( ',', '.', $cost ) );
if ( '' === $cost ) { // empty is not zero - skip it
$skipped++;
continue;
}
if ( ! is_numeric( $cost ) || (float) $cost < 0 ) {
WP_CLI::warning( "Bad cost value: '{$cost}' (id={$id}, sku={$sku})" );
$failed++;
continue;
}
$id = (int) $id;
if ( ! $id && $sku ) {
$id = wc_get_product_id_by_sku( trim( $sku ) );
}
$product = $id ? wc_get_product( $id ) : null;
if ( ! $product ) {
WP_CLI::warning( "Product not found (id={$id}, sku={$sku})" );
$failed++;
continue;
}
if ( $DRY_RUN ) {
WP_CLI::log( sprintf( '[dry run] %d %s: %s -> %s',
$product->get_id(), $product->get_name(),
var_export( $product->get_cogs_value(), true ), $cost ) );
} else {
$product->set_cogs_value( (float) $cost );
$product->save();
WP_CLI::log( sprintf( '%d %s = %s', $product->get_id(), $product->get_name(), $cost ) );
}
$written++;
}
fclose( $handle );
WP_CLI::success( sprintf( '%s: %d, skipped (empty cost): %d, failed: %d',
$DRY_RUN ? 'To write' : 'Written', $written, $skipped, $failed ) );
Save it as fill-costs.php next to costs.csv and run:
wp eval-file fill-costs.php costs.csv
The script is here to be read, not downloaded in one click—deliberately. It writes to your database, so it should pass your eyes before it passes your products.
Why not a shell loop. The tempting wp eval called once per row boots the whole of WordPress
for every product: at five hundred products that is a quarter of an hour instead of a few seconds,
and five hundred chances to break halfway. One script, one boot.
If you have no SSH, use the product import above. For developers: the same pair of methods,
set_cogs_value() and save(), works anywhere you can run PHP inside WordPress. The REST API
carries the same value on the products and variations resources, as cost_of_goods_sold with values, total_value and—on
variations — defined_value_is_additive. Two things to know before you write a loop against it:
effective_value and total_value are read-only, and an empty values array means a cost of
zero, with everything that implies further down this page. Read one product back
(GET /wp-json/wc/v3/products/<id>) and check the shape against your own version first.
The trial run worth not skipping
This applies to both routes.
- A database backup. Not a “product export”—a backup. Both routes write, and saving a product can touch more than one field.
- Ten rows first. Copy ten lines into a trial file and run the whole thing on them (with the script: dry, then for real), then look at those ten products in the admin.
- Only then the full file (with the script,
$DRY_RUN = false). - Verify afterwards—in the store, not in the spreadsheet. Place one test order for a product with a cost and check that the order stored it. That is the only test that covers the whole chain rather than the field in the product record.
Variations—decide these yourself
A variation inherits the parent product’s cost until it has one of its own. Its own cost then replaces the parent’s. WooCommerce can also add it on top of the parent’s cost, but that mode has no switch in the admin: it can be set only through the REST API or in code. Which one you want is a decision about what the number means, not what it is, so neither the script nor the import makes it.
In practice: bulk-fill the costs of parent products, and only touch variations where the cost genuinely differs, one at a time in the product editor, where you can see it. A shirt costing 24 with an “embroidered” variation at 3 comes to 3 in the default replace mode, and to 27 in additive mode. In the product import, a cost in a variation row becomes that variation’s own cost; leave the cell empty to keep the parent’s. Details in costs on variations.
One thing to know when checking your results: WooCommerce’s helper column stores the entered value, not the effective one, so a variation happily inheriting its parent’s cost looks like a variation with no cost in a SQL query. Any “products without cost” list built straight on that column will be full of false alarms.
What this will not fix
- History. Orders placed before you entered the costs stay without cost forever; there is no backfill, and that is not an oversight.
- Freebies. A product that genuinely costs zero is stored as no cost at all, because core deletes the value instead of writing a zero. It will stay on the missing-cost list and there is nothing you can do about it.
- Refunds. Issuing a refund makes WooCommerce recalculate the cost of every line on the original order from today’s product cost—so freshly entered costs can rewrite the very history they describe. What happens then.
- Other costs. Shipping, payment gateway fees, and returns to the supplier are not cost of goods, and the cost field does not cover them. Gross profit is not net profit and we do not pretend otherwise.
Checklist
- The cost feature switched on—without it none of the rest does anything.
- One definition of cost, written down.
- Export products: ID, SKU, and Cost of goods for the import, or
id,sku, and an emptycostcolumn for the script. - Sort by revenue, fill from the top.
- Backup, trial on ten rows, only then the whole file. In the import, delete rows instead of leaving the cost empty.
- A test order to check the whole chain.
- Variations separately and deliberately—replace mode or additive mode.
If any step works differently in your store, let us know. These pages get corrected when they turn out to be wrong.