WordPress upload post and attach file (wp_insert_post and wp_insert_attachment)

WordPress upload post and attach file (wp_insert_post and wp_insert_attachment)

Dear readers,

My current Custom WordPress theme doesn’t allow me to attach an image / .pdf by to a post.

This form (method=”POST”) has a ‘subject’ and ‘textarea’ field and ofcourse an input type=”file”.

What does work is create a post by using: ‘wp_insert_post’

  • and get the ID of the newest post

What somewhat works after uploading the form:

  • get the image to reserve space at myWebsiteUrl/wp-admin -> media (but it doesn’t show up, rather a WordPress template image, which is all gray, is shown).

What doesnt work is getting the uploaded file to insert itself to the ‘wp-content/uploads’ folder

Furthermore in SQL database: when I go to: wp_posts and then observe column ‘post_content’, the post is there, but nothing (not even template code of the image) is shown other then the form subject and textarea content.

Please keep in mind this is a custom WordPress theme (which I have made). My page templates are stored in de folder called ‘pages’ and within those pages I require the page parts from the folder called ‘pageParts’.

My theme dir: “./wp-content/theme/myTheme/” The (view) page the form is in: “myTheme/pages/upload.php” And the above HTML code (partial) is required_once from: “myTheme/ pageParts/uploadPart.php”

Now for the code (PHP 8)

My html form file:
<?php session_start(); ?> <html> <body> <form action="../pages/uploadenPagesGet.php" method="POST" enctype="multipart/form-data"> <input id="titelText" name="titel" type="text" placeholder="Titel"> <select id = "mainSelect" name = "selectedOnderwerp"> <option value = "5">Constructions</option> </select> <textarea name="berichtTextarea" placeholder="Please enter your message&#46;&#46;&#46;"></textarea> <input id="buttonSubmit" class="buttonGold buttonSubmit center" type="submit" value="Save"> </form> </body> </html>

Then onto my uploadenPagesGet.php

session_start();
// required for uploading
require_once '../../../../wp-load.php';
require_once '../../../../wp-admin/includes/file.php';

require_once( ABSPATH . '../../../wp-admin/includes/image.php' );
require_once( ABSPATH . '../../../wp-admin/includes/media.php' );

// Retrieve the FORM data:
global $user_ID;
global $post;
global $post_id;

$titel             = $_POST ['titel'                    ];
$selectedOnderwerp = $_POST ['selectedOnderwerp'        ];
$berichtTextarea   = $_POST ['berichtTextarea'          ];
$uploadedFileValue = $_FILES['uploadedFileValue'        ];
$filename          = $_FILES['uploadedFileValue']["name"];

//Preparing the INSERT with the FORM data:

$new_post = array(
  'post_title' => $titel,
  'post_content' => $berichtTextarea,
  'post_status' => 'publish',
  'post_date' => date('Y-m-d H:i:s'),
  'post_author' => $user_ID,
  'post_type' => 'post',
  'post_category' => array($selectedOnderwerp),
);

// And then I successfully create a post which is visible in Wordpres's Posts on the front and backend

$post_id = wp_insert_post($new_post);

// Now it is correct that I haven't sanitized anything at this point, but that is beyond the scope of what I'm
// asking. I will do that and much more (for example CSRF) after this ticket is resolved. 
// I kindly urge you to to not advice me on security. 

//So the data (all except the $_FILES) are uccesfully posted. Now I get the ID of my post

$currentPostID = $post_id;
echo $currentPostID; // display's the ID of the post.
//exit;     remove the comment to see the ID if needed, and or uncomment to post succesfully.


//set and place image in upload folder: 
$file_id = $uploadedFileValue;
$post_id = $currentPostID;
$file = wp_handle_upload( $file_id, $post_id);

//Define upload
$wp_upload_dir = wp_upload_dir();

// check absolute filename
$filetype = wp_check_filetype( basename( $filename ), null );

//Create array of data to attach the the WordPress hook later

$attachment = array(
  'guid'           => $wp_upload_dir['url'] . "https://stackoverflow.com/" . basename( $filename ),
  'post_mime_type' => $filetype['type'],
  'post_title'     => preg_replace( '/.[^.]+$/', '', basename( $filename ) ),
  'post_content'   => '',
  'post_status'    => 'inherit'
);

//insert data into the hook
$attachment_id = wp_insert_attachment( $attachment, $filename, $currentPostID);

//Attach previous information to the hook:
$attach_data = wp_generate_attachment_metadata( $attachment_id, get_attached_file( $attachment_id ));

//execute hooks by updating:
wp_update_attachment_metadata( $attachment_id, $attach_data );
    ```

Unfortunately the above returns gives error:
getimagesize(myWebsite.com/wp-content/uploads/clouds2.png): 
Failed to open stream: No such file or directory in (myWebsite.com/wp-content/wp-includes/media.php) on line 5165 

Warning: exif_imagetype(myWebsite.com/wp-content/uploads/clouds2.png): Failed to open stream: No such file or directory in (myWebsite.com/wp-includes/functions.php) on line 3245 

Warning: fopen(myWebsite.com/wp-content/uploads/clouds2.png): Failed to open stream: No such file or directory in (myWebsite.com/wp-includes/functions.php) on line 3268

I have tried the following urls:


wp_generate_attachment_metadata()
media_handle_upload()
wp_check_filetype()
wp_insert_post()
wp_generate_attachment_metadata()
And many more but for the sake of the length of this article: two StackOverflow posts which answers strangely enough do not apply to me. https://stackoverflow.com/search?q=wp_insert_attachment https://stackoverflow.com/questions/34792678/using-wp-insert-post-and-wp-insert-attachment-at-the-same-time https://stackoverflow.com/questions/57064696/wordpress-insert-attachment-with-current-full-path-to-image-not-located-in-word Thank you for reading the problem and I hope you can help me by resolving the issue.

Leave a Comment