WordPress upload post and attach file (wp_insert_post and wp_insert_attachment)

  • Unknown's avatar

    My current Custom WordPress theme doesn’t allow me to attach an image / .pdf by <form> 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 grey, is shown).

    What doesn’t work is getting the uploaded file to insert itself to the ‘wp-content/uploads’ folder so I can attach it to the new post. Later on I want to get the post and show it on another page and style it by using CSS

    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.

    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 is in: “myTheme/pages/upload.php”
    * and the FORM HTML code (partial) is required_once into that (view) from: “myTheme/pageParts/uploadPart.php”

    Now for the code (PHP 8)

    My html form file:

    html
    <?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..."></textarea>
        <input id="buttonSubmit" class="buttonGold buttonSubmit center" type="submit" value="Save">
      </form>
     </body>
    </html>
    

    uploadenPagesGet.php

    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'] . '/' . 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 in research:

    – [https://developer.wordpress.org/reference/functions/wp_generate_attachment_metadata/][1]

    – [https://developer.wordpress.org/reference/functions/media_handle_upload/][2]

    – [https://developer.wordpress.org/reference/functions/wp_check_filetype/][3]

    – [https://developer.wordpress.org/reference/functions/wp_insert_post/][4]

    – [https://developer.wordpress.org/reference/functions/wp_generate_attachment_metadata/][1]

    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][5]

    – [https://stackoverflow.com/questions/34792678/using-wp-insert-post-and-wp-insert-attachment-at-the-same-time][6]

    – [https://stackoverflow.com/questions/57064696/wordpress-insert-attachment-with-current-full-path-to-image-not-located-in-word][7]

    [1]: https://developer.wordpress.org/reference/functions/wp_generate_attachment_metadata/
    [2]: https://developer.wordpress.org/reference/functions/media_handle_upload/
    [3]: https://developer.wordpress.org/reference/functions/wp_check_filetype/
    [4]: https://developer.wordpress.org/reference/functions/wp_insert_post/
    [5]: https://stackoverflow.com/search?q=wp_insert_attachment
    [6]: https://stackoverflow.com/questions/34792678/using-wp-insert-post-and-wp-insert-attachment-at-the-same-time
    [7]: https://%20https://stackoverflow.com/questions/57064696/wordpress-insert-attachment-with-current-full-path-to-image-not-located-in-word

    Thank you for still being here and and I hope you can help me by resolving the issue please.

  • Unknown's avatar

    We can’t help you as your site isn’t running on the wordpress.com platform but uses the open source wordpress.org. Their support is at https://wordpress.org/support/forums/

  • Unknown's avatar
  • The topic ‘WordPress upload post and attach file (wp_insert_post and wp_insert_attachment)’ is closed to new replies.