3

I've made a quick PHP script/page that uses the wp_insert_post() function to insert a post directly. And this works great. The post I am manually adding has an image in it, so I firstly manually/programatically upload the image to the respective "/uploads/" folder where all my post images are saved (btw im not using year/month sub-directories). The content of the post has normal text, plus the necessary HTML to point to the image too, eg.

<p>This is a manually created post for my blog, there should be a picture below this line of text.  Thanks for visiting.</p>
<img src="http://www.mysite.com/wp-content/uploads/image.jpg">

The post appears fine (including the image). But my 2 problems are:

1) The image I uploaded is not in the Media Library, How do I get it in there?

2) I would like to add a "featured image/thumbnail" to the same image, but I dont know what function is used to make that call? I was hoping to find a function along the lines of insert_featured_thumbnail("/wp-content/uploads/image.jpg", $pid)

Does anyone have any ideas?

Thanks in advanced.

WizzKidd

3

Function Reference/wp insert attachment

$image_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

This function will return an image id which you can use for the featured image.

update_post_meta($post_id, "_thumbnail_id", $image_id);
2

Thank you for your answer. It was spot on. I'm now using the following code:

//SAVE THE POST - $new_post is my array that conforms to the necessary requirements
$pid = wp_insert_post($new_post);

//SET MY TAGS UP PROPERLY - $tagsArray contains an array of tags
wp_set_post_tags($pid, $tagsArray);

//ADD IMAGE TO IMAGE-GALLERY AND return $image_id - $wp_image is my image filename
$wp_filetype = wp_check_filetype(basename($wp_image), null);
$attachment = array(
   'post_mime_type' => $wp_filetype['type'],
   'post_title'     => preg_replace('/\.[^.]+$/', '', $myImageTitle),
   'post_content'   => '',
   'post_status'    => 'inherit'
);
$serverFullPath = '/home/user/public_html/mysite/wp-content/uploads/';
$image_id = wp_insert_attachment($attachment, $serverFullPath . $wp_image, $pid);

//ADD THE MEDIA GALLERY IMAGE AS A FEATURED IMAGE FOR THIS POST
update_post_meta($pid, "_thumbnail_id", $image_id);

//POST THE POST
do_action('wp_insert_post', 'wp_insert_post');

I checked the Media Gallery, and my image is there :) although it doesn't specify the author of the file unlike the other images which show 'admin'.

Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.