No complete code, but I know you can stick it together. 🙂
-
Find all post IDs of unattached images (borrowed from
wp-admin/upload.php
):global $wpdb; $lost = $wpdb->get_col( " SELECT ID FROM $wpdb->posts WHERE post_type="attachment" AND post_parent > '0' AND post_parent NOT IN ( SELECT ID FROM $wpdb->posts WHERE post_type NOT IN ( 'attachment', '" . join( "', '", get_post_types( array( 'public' => false ) ) ) . "' ) ) " );
-
Get image URLs for all post IDs: Since these attachments have no parent their URL is equivalent to
get_the_guid()
(that’s one of the two reasons the GUID looks like an URL, I don’t like that).$urls = array (); foreach ( $lost as $id ) $urls[ $id ] = get_the_guid( $id );
-
Now find posts with those images and attach the images to these posts:
global $wpdb; foreach ( $urls as $id => $url ) { $posts = get_posts( array ( 's' => $url, 'numberposts' => 1 ) ); if ( ! $posts ) continue; $parent_id = $posts[0]->ID; $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_parent = %d WHERE post_type="attachment" AND ID = %d", $parent_id, $id ) ); }
Not tested, see it just as hints.