I am creating some custom post creation pages with PHP.

I create a simple post and want to attach an image I already have on my server to the post without moving it into the upload directory. I am trying to do it this way.


$newPostID = wp_insert_post($post,$wp_error);

$attachment = array(
                    'guid' => $imageURL,
                    'post_mime_type' => $filetype['type'],
                    'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $imageURL ) ),
                    'post_content' => '',
                    'post_status' => 'inherit'
$attach_id = wp_insert_attachment($attachment, $imageURL, $newPostID);

Where $imageURL is the path to my image file.

When I do this and check the Media Library, there is an entry for this file, but for its URL, it has my upload directory prefixed to $imageURL. Like http://domain/uploads/http://domain/myRealImageFolder

Is there away to achieve what I want without copying the file into the upload folder?

EDIT: I should add that in the database.wp_posts, the entry for my attachment has a guid value that is the correct URL that I need.

  • 2
    You have seen that on the Codex it says: "The file MUST be on the uploads directory."
    – kraftner
    Jan 30, 2015 at 9:39
  • Ah. No I had not. Would not have submitted the question otherwise. Thanks. Cheers. Jan 30, 2015 at 10:17


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.