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:

One thought on “Insert an image into a WordPress Post with a plugin.

  1. How can I resize the image when shown it the post
    Iam using lightbox and need the uploaded image to have to versions
    one is resized to be shown and the other is the link to original that will be used by kight box

    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>