Created
November 24, 2023 11:08
-
-
Save rwkyyy/a192e5ee621f59a11ef6296991af15da to your computer and use it in GitHub Desktop.
Command to clean empty images (undefined) from products gallery (WooCommerce) after they have been removed from media library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// needs to be run via cli with: | |
// wp cleanup-all-galleries | |
if (defined('WP_CLI') && WP_CLI) { | |
class Cleanup_All_Product_Galleries_Command { | |
public function __invoke($args, $assoc_args) { | |
$args = array( | |
'post_type' => 'product', | |
'posts_per_page' => -1, | |
'fields' => 'ids', | |
); | |
$product_ids = get_posts($args); | |
foreach ($product_ids as $product_id) { | |
$product = wc_get_product($product_id); | |
if (!$product) continue; | |
$gallery_image_ids = $product->get_gallery_image_ids(); | |
$valid_image_ids = array_filter($gallery_image_ids, 'wp_attachment_is_image'); | |
if (count($gallery_image_ids) !== count($valid_image_ids)) { | |
$product->set_gallery_image_ids($valid_image_ids); | |
$product->save(); | |
WP_CLI::line("Gallery updated for product ID $product_id."); | |
} | |
} | |
WP_CLI::success("Completed updating galleries for all products."); | |
} | |
} | |
WP_CLI::add_command('cleanup-all-galleries', 'Cleanup_All_Product_Galleries_Command'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment