0

This is the php I have for a form which creates a post with thumbnail. I want to know how to add the uploaded image to the post content as well. Tried a few things, but they didn't work.

 if(isset($_POST['new_post']) == '1') {

        $post_title = $_POST['post_title'];
        $post_category = $_POST['cat'];
        $filename = $_POST['attach'];

       $new_post = array(
          'ID' => '',
          'post_author' => $current_user->ID, 
          'post_category' => array($post_category),
          'post_title' => $post_title,
          'post_status' => 'draft'
        );

        $post_id = wp_insert_post($new_post);
        $post = get_post($post_id);
        $new_post = $post->ID;

     if (!function_exists('wp_generate_attachment_metadata')){
            require_once(ABSPATH . "wp-admin" . '/includes/image.php');
            require_once(ABSPATH . "wp-admin" . '/includes/file.php');
            require_once(ABSPATH . "wp-admin" . '/includes/media.php');
            }

             if ($_FILES) {
            foreach ($_FILES as $file => $array) {
                if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
                    return "upload error : " . $_FILES[$file]['error'];
                }
                $attach_id = media_handle_upload( $file, $new_post );
            }   
            }

            if ($attach_id > 0){

            //and if you want to set that image as Post  then use:
            update_post_meta($new_post,'_thumbnail_id',$attach_id);
            }

}

2 Answers 2

1

The content of the post is just that - the value of post_content field.

You could retrieve HTML for attachment by wp_get_attachment_image() and either pass it to wp_insert_post() initially (will need to create attachment earlier for that) or use wp_update_post() to assign content to already existing post.

1
  • I don t get it ... I tried a few times but it's not working. Can you post an example please? Or edit my code.
    – Ciprian
    Commented Sep 14, 2013 at 15:44
1

The following code adds the image right at the beginning of your post. You can edit it in order to add the image wherever you need.

$get_post = get_post($new_post);
$post_content = $get_post->post_content;
$post_id = $getPost->ID;
$new_attach = wp_get_attachment_image($attach_id);
$post_content = $new_attach.$post_content;
$post_data = array('ID'=>$post_id,'post_content'=>$post_content);
wp_update_post($post_data);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.