Insert an image into a WordPress Post with a plugin.
So in a project I’m working on I need to use a normal form to insert a post into the database. My client wanted the form to also add an image to the post. Furthermore, the image must be inserted using normal WordPress methods.
The code below is the minimum required to insert an image into the database and attach it to a specific post. include_once(ABSPATH.'/wp-admin/includes/media.php'); include_once(ABSPATH.'/wp-admin/includes/file.php'); include_once(ABSPATH.'/wp-admin/includes/image.php');
// $id is the id of the post being inserted
// $name is actually the name of the form input that uploaded the file so WP can access it using $_FILE[$name]
media_handle_upload($name,$id);
If you are inserting a new post, it makes sense to have the line $id = wp_insert_post($post_data);
before this.
Categorized as: