Last active
May 10, 2017 19:44
-
-
Save gthayer/db72a76d9066c2f53d990b83a44dba83 to your computer and use it in GitHub Desktop.
Remove product thumbnail IDs from galleries.
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
/* | |
* Removes the product's thumbnail from the gallery if it's set in both. Useful after the Woo 3.0 update as the system now automatically add the image to the gallery. | |
* Drop this snippet in functions.php, reload the page, then delete the function. | |
*/ | |
add_action( 'init', 'remove_duplicate_gallery_images' ); | |
function remove_duplicate_gallery_images() { | |
// Get the products. | |
$args = array( 'post_type' => 'product', 'posts_per_page' => -1 ); | |
$products = get_posts( $args ); | |
// Loop 'em. | |
foreach ( $products as $product ) { | |
// Get the product object. | |
$_product = wc_get_product( $product->ID ); | |
// Get the image IDs. | |
$thumbnail = get_post_thumbnail_id( $_product->get_id() ); | |
$gallery = $_product->get_gallery_image_ids(); | |
// Ignore empty galleries. | |
if ( empty( $gallery ) ) { | |
continue; | |
} | |
// Check if the thumbnail ID is in the gallery. | |
if ( ( $key = array_search( intval( $thumbnail ), $gallery ) ) !== false ) { | |
// If so, remove it and update the product. | |
unset( $gallery[$key] ); | |
$_product->set_gallery_image_ids( $gallery ); | |
$_product->save(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment