Export a Stock Report to CSV
Adds a one-click stock report download under WooCommerce > Stock report, listing every product and variation with SKU, stock status, quantity and price.
Opens WPIDE on
Code
add_action( 'admin_menu', function () {
add_submenu_page( 'woocommerce', 'Stock report', 'Stock report', 'manage_woocommerce', 'wpide-stock-report', function () {
?>
<div class="wrap">
<h1><?php echo esc_html( 'Stock report' ); ?></h1>
<p><?php echo esc_html( 'Download the stock level of every product and variation as a CSV file.' ); ?></p>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
<input type="hidden" name="action" value="wpide_export_stock">
<?php wp_nonce_field( 'wpide_export_stock' ); ?>
<?php submit_button( 'Download CSV', 'primary', 'submit', false ); ?>
</form>
</div>
<?php
}, 61 );
} );
add_action( 'admin_post_wpide_export_stock', function () {
global $wpdb;
check_admin_referer( 'wpide_export_stock' );
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_die( esc_html( 'You are not allowed to export stock.' ), 403 );
}
$rows = $wpdb->get_results(
"SELECT p.ID, p.post_title, p.post_parent, l.sku, l.stock_status, l.stock_quantity, l.min_price
FROM {$wpdb->posts} p
INNER JOIN {$wpdb->wc_product_meta_lookup} l ON l.product_id = p.ID
WHERE p.post_type IN ('product','product_variation') AND p.post_status = 'publish'
ORDER BY COALESCE(NULLIF(p.post_parent, 0), p.ID), p.post_parent, p.ID"
);
$cell = function ( $value ) {
$value = (string) $value;
return preg_match( '/^[=+\-@\t\r]/', $value ) ? "'" . $value : $value;
};
nocache_headers();
header( 'Content-Type: text/csv; charset=utf-8' );
header( 'Content-Disposition: attachment; filename=stock-' . gmdate( 'Y-m-d' ) . '.csv' );
$out = fopen( 'php://output', 'w' );
fwrite( $out, "\xEF\xBB\xBF" );
fputcsv( $out, array( 'ID', 'Parent ID', 'Product', 'SKU', 'Stock status', 'Quantity', 'Price' ) );
foreach ( $rows as $row ) {
fputcsv( $out, array_map( $cell, array( $row->ID, $row->post_parent ? $row->post_parent : '', $row->post_title, $row->sku, $row->stock_status, null === $row->stock_quantity ? '' : (float) $row->stock_quantity, $row->min_price ) ) );
}
fclose( $out );
exit;
} );
Notes
Reads WooCommerce's product lookup table, so even large catalogues export quickly.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.