Insert an image into a WordPress Post with a plugin.

Posted on Thursday the 15th of October, 2009 at 3:15 pm in Dev

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.

  1. include_once(ABSPATH.'/wp-admin/includes/media.php');
  2. include_once(ABSPATH.'/wp-admin/includes/file.php');
  3. include_once(ABSPATH.'/wp-admin/includes/image.php');
  4. // $id is the id of the post being inserted
  5. // $name is actually the name of the form input that uploaded the file so WP can access it using $_FILE[$name]
  6. 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.

  1. mohamed posted the following on October 1, 2011 at 2:21 pm.

    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

    Reply to mohamed

Leave a reply

:) :D :( :o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: ;) :!: :?: :idea: :arrow: :| :mrgreen: