How can I attach hotlinked images in posts/pages within the same server?

Not sure if this makes sense but I’m trying to attach hotlinked images to their posts/pages with no lucky, most plugins such Cache images works ok but only to external domains, I need to auto-attach hotlinked images in the same domain/server.

Addendum: This happened duo copying-pasting content from static html files into WP pages and posts.

Read More

Thanks for any clue!

Related posts

Leave a Reply

2 comments

  1. No complete code, but I know you can stick it together. 🙂

    1. 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 ) ) ) . "' )
          )
      " );
      
    2. 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 );
      
    3. 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.

  2. Thanks @toscho, I think I figured how your code can work (that can take time hahah), firstly import images files within server (Add form server plugin can do this or can use a custom script), find image paths within every post/page that match filenames now in media library, then attach them.

    I can’t use this because there where different imagens but same filenames along different folders (also some problems with filenames using spaces), then I had to use this plugin, you must visit/edit every page/post and download the images, that can be a pain but at least will work with files wherever they are (same doamin for example), surely there is someway to hack this plugin to work on every post on page.

    (If image filenames has spaces this plugin still will return empty images and you need to re-edit it manually, don’t know why WP can diplay hotlinked images with strange filenames)