Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Remove all WooCommerce products from database via SQL
<?php
require dirname(__FILE__).'/wp-blog-header.php';
//Removing attributes (does not work for some reason, should read up on https://www.webhat.in/article/woocommerce-tutorial/how-product-attribute-are-stored-in-database/)
$wpdb->query("DELETE FROM wp_terms WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE taxonomy LIKE 'pa_%')");
$wpdb->query("DELETE FROM wp_term_taxonomy WHERE taxonomy LIKE 'pa_%'");
$wpdb->query("DELETE FROM wp_term_relationships WHERE term_taxonomy_id NOT IN (SELECT term_taxonomy_id FROM wp_term_taxonomy)");
//Removing products and product variations
$wpdb->query("DELETE FROM wp_term_relationships WHERE object_id IN (SELECT ID FROM wp_posts WHERE post_type IN ('product','product_variation'))");
$wpdb->query("DELETE FROM wp_postmeta WHERE post_id IN (SELECT ID FROM wp_posts WHERE post_type IN ('product','product_variation'))");
$wpdb->query("DELETE FROM wp_posts WHERE post_type IN ('product','product_variation')");
//Removing orphaned postmeta
$wpdb->query("DELETE pm FROM wp_postmeta pm LEFT JOIN wp_posts wp ON wp.ID = pm.post_id WHERE wp.ID IS NULL");
//Removing other stuff: product_cat, product_type, product_tag
$wpdb->query("DELETE FROM wp_termmeta WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE taxonomy IN ('product_cat', 'product_type', 'product_tag', 'product_visibility'))");
$wpdb->query("DELETE FROM wp_terms WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE taxonomy IN ('product_cat', 'product_type', 'product_tag', 'product_visibility'))");
$wpdb->query("DELETE FROM wp_term_taxonomy WHERE taxonomy in ('product_cat', 'product_type', 'product_tag', 'product_visibility')");
$wpdb->query("DELETE meta FROM wp_termmeta meta LEFT JOIN wp_terms terms ON terms.term_id = meta.term_id WHERE terms.term_id IS NULL");
$wpdb->query("DELETE FROM wp_woocommerce_attribute_taxonomies");
$wpdb->query("DELETE FROM wp_woocommerce_sessions");
echo 'Products, Product Caetgories, Product Tags should be deleted. Check Product Attributes they might not be.';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment