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.

Related posts

  1. barnettbarr posted the following on December 26, 2009 at 6:47 am.

    such a nice info for me…
    Acnezine

    Reply to barnettbarr
  2. aphen posted the following on December 30, 2009 at 3:36 pm.

    aaaa :? aa :oops: :cry: :D :Dsleep 10

    Reply to aphen

Leave a reply

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