Skip to content

Instantly share code, notes, and snippets.

@Acephalia
Created March 9, 2024 03:39
Show Gist options
  • Save Acephalia/4c247bebd751e15bb9023c22074d9476 to your computer and use it in GitHub Desktop.
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 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 );
@Acephalia
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment