Created
March 9, 2024 03:39
-
-
Save Acephalia/4c247bebd751e15bb9023c22074d9476 to your computer and use it in GitHub Desktop.
Woocommerce Fix CSV Imported Images Showing Up As Unattached In Media Gallery
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
//This script will reattach media files to their relvant products (when you open and update a product) that do not get assigned when you import via a csv. | |
add_action( 'woocommerce_process_product_meta', function ( $post_id, $post ) { | |
global $wpdb; | |
$attachment_ids = isset( $_POST['product_image_gallery'] ) ? array_filter( explode( ',', wc_clean( $_POST['product_image_gallery'] ) ) ) : array(); | |
// update posts in the $attachment_ids array to have post_parent = $post_id | |
$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_parent = %d WHERE ID IN (" . implode( ',', $attachment_ids ) . ")", $post_id ) ); | |
}, 21, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original code by plexus77 : woocommerce/woocommerce#27281 (comment)
To auto run this for all products use bulk resave: https://gist.github.com/Acephalia/8e49a2176cdadbd43e73a1b264bb6f03