Programmatically adding Wordpress post with attachment

https://stackoverflow.com/questions/3805603/programmatically-adding-wordpress-post-with-attachment

84

I am getting post_title, post_content and other things in $_REQUEST as well as an image file. I want to save all that as a post in the wordpress database. I have on my page

<?php
require_once("wp-config.php");
$user_ID; //getting it from my function
$post_title = $_REQUEST['post_title'];
$post_content = $_REQUEST['post_content'];
$post_cat_id = $_REQUEST['post_cat_id']; //category ID of the post
$filename = $_FILES['image']['name'];

//I got this all in a array

$postarr = array(
 'post_status' => 'publish',
 'post_type' => 'post',
 'post_title' => $post_title,
 'post_content' => $post_content,
 'post_author' => $user_ID,
 'post_category' => array($category) 
 );
$post_id = wp_insert_post($postarr);

?>

This will get all the things in database as post but I don't know how to add the attachment and its post meta.

How can I do that? Can anybody help me? I am really confused and have spent a few days trying to solve this.phpwordpressShareImprove this questionFollowedited Sep 10 '17 at 5:19Cœur32.3k2121 gold badges173173 silver badges231231 bronze badgesasked Sep 27 '10 at 16:00Salman Khimani51522 gold badges77 silver badges2121 bronze badges

Add a comment

2 Answers

ActiveOldestVotes8

To add an attachment, use wp_insert_attachment():

https://developer.wordpress.org/reference/functions/wp_insert_attachment/

EXAMPLE:

To add Meta Data, use wp_update_attachment_metadata():

https://developer.wordpress.org/reference/functions/wp_update_attachment_metadata/ShareImprove this answerFollowedited Jul 5 '20 at 16:46matty1,2891212 silver badges2121 bronze badgesanswered Sep 27 '10 at 16:55Todd Moses10.8k1010 gold badges4444 silver badges6464 bronze badges

  • 1i think it it just a copy paste from that url..... can u tell me how can i use my variables in it? Will it upload image coming through request to the wp-content/uploads ?? – Salman Khimani Sep 28 '10 at 6:00

  • $post_content goes to post_content, $post_id you get from the post insert, etc... – Todd Moses Sep 28 '10 at 17:22

Add a commentReport this ad1

If you need to upload the attachment as well as inserting it into the database, you should use media_handle_upload(), which will do all of that for you. All you have to do is give it the index of the file in the $_FILES array and the ID of the parent post:

ShareImprove this answerFollowedited Jul 5 '20 at 20:53

Last updated

Was this helpful?