If you have a big blog, with lots of images, you have noticed entering your gallery you have some images un-attached to their posts. I’ve looked for a script to attach them back to posts in order to find the orphaned images and couldn’t find one suitable for WordPress 3.X. I’ve turned to Leo Radoiu, a programmer friend of mine, for a solution.

First, he created a routine on my database named udsp_RepairImages

DROP PROCEDURE `udsp_RepairImages`//
CREATE DEFINER=`user`@`localhost` PROCEDURE `udsp_RepairImages`()
BEGIN
    DECLARE _attach_id BIGINT DEFAULT 0;
    DECLARE _attach_guid VARCHAR(255);
    DECLARE _parent_id BIGINT DEFAULT 0;
    DECLARE _done INT DEFAULT 0;

    BEGIN
        DECLARE cur_attach CURSOR FOR SELECT ID, guid FROM wp_posts WHERE post_parent = 0 AND post_type = ‘attachment’;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = 1;
        OPEN cur_attach;

        REPEAT
            FETCH cur_attach INTO _attach_id, _attach_guid;
   
            IF (_done = 0) THEN
                SELECT ID INTO _parent_id FROM wp_posts WHERE post_content LIKE CONCAT(‘%’, _attach_guid, ‘%’) AND post_type = ‘post’ LIMIT 0,1;

                     IF (_parent_id IS NOT NULL) THEN
                    UPDATE wp_posts SET post_parent = _parent_id WHERE ID = _attach_id AND post_type = ‘attachment’;                                END IF;
                SET _done = 0;

            END IF;
            UNTIL (_done = 1)
        END REPEAT;
        CLOSE cur_attach;
        SET _done = 0;
    END;
END

Change ‘user’ to your database user.

And a small php file that can be called and solves the problem.  Change user, pass and database to your own.

<?php
    $id_server = mysqli_connect(‘localhost’, ‘user’, ‘pass’, ‘database);

    if(isset($id_server)) {
        $sql = "CALL udsp_RepairImages()";
        $query = mysqli_query($id_server, $sql);

        var_dump($query);

        mysqli_next_result($id_server);
    }
?>

Et voila!