I have the current problem : I run a WordPress website with Woo Commerce and every few days I refresh the product list deleting and importing over 8000 products at a time .
Now, every single time I get +/- 3500 products deleted from the database so I have to remove the photos and the thumbnails for each one .. so i have to delete more then 12.000 photos .
Using any plugin is not an option, they all freeze / stop working so I need to build my own / function or plugin and I need a starting point .
I have a list with the old products and I delete them like this :
foreach($old_product_list as $oldproduct){
$wpdb->show_errors();
$delq = $wpdb->get_results(
" DELETE a,b,c
FROM wp_posts a
LEFT JOIN wp_term_relationships b ON ( a.ID = b.object_id )
LEFT JOIN wp_postmeta c ON ( a.ID = c.post_id )
LEFT JOIN wp_term_taxonomy d ON ( d.term_taxonomy_id = b.term_taxonomy_id )
LEFT JOIN wp_terms e ON ( e.term_id = d.term_id )
WHERE a.post_title='".$mysqli->real_escape_string($oldproduct['name'])."' " );
[…..]
As a rule, I suggest you try to stick as much as possible to WordPress core functions when modifying the database, as they will handle associated data automatically – e.g. delete associated post meta, associated taxonomy info, etc.
(Woocommerce stores product image data as product post_meta, see below for details.) This might slow things down in comparison to direct access to the database, but the database will be much cleaner as a result.
Needless to say, do backup your database before trying any of this…
First, you need to work with post ids.
Now, there are three different things you may want to delete, in increasing order of ‘destructiveness’:
the images from WordPress media Gallery
Point 1. This one is easy. But to do it right, you need to use wordpress functions, as the code comments hopefully make clear.
Points 2 and 3, simple case.
If your images are all unique to each product and not linked from anywhere, their post_parent will be the product_id, so you can use this version of https://wordpress.stackexchange.com/a/109803/40965, modified to bypass the trash:
The last line makes sure that this function is called whenever wp_delete_post is called, so you don’t need to change the solution to point 1 above.
Points 2 and 3, general case. If some images are shared among products (some of which are perhaps not deleted in the current batch), or linked from other posts, the above solution will break things.
Here is where we need to understand how Woocommerce handles product images. The images associated to a product are stored as post_meta ‘_thumbnail_id’ and ‘_product_image_gallery’ for the product’s post ID.
_thumbnail_id
is the post_id of the image (post with post_type=’attachment’);_product_image_gallery
is a comma-separated string of image post ids.Just to get you started, here is how to get all the attachment post ids to handle.
And here comes the hard part: apply the solution above only to images that can be safely deleted.