• Resolved AndradeL

    (@womday)


    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.www.ads-software.com/reference/functions/wp_generate_attachment_metadata/][1]

    – [https://developer.www.ads-software.com/reference/functions/media_handle_upload/][2]

    – [https://developer.www.ads-software.com/reference/functions/wp_check_filetype/][3]

    – [https://developer.www.ads-software.com/reference/functions/wp_insert_post/][4]

    – [https://developer.www.ads-software.com/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.www.ads-software.com/reference/functions/wp_generate_attachment_metadata/
    [2]: https://developer.www.ads-software.com/reference/functions/media_handle_upload/
    [3]: https://developer.www.ads-software.com/reference/functions/wp_check_filetype/
    [4]: https://developer.www.ads-software.com/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.

    • This topic was modified 2 years, 6 months ago by James Huff.
    • This topic was modified 2 years, 6 months ago by Jan Dembowski. Reason: Formatting
Viewing 8 replies - 1 through 8 (of 8 total)
  • Thread Starter AndradeL

    (@womday)

    I can’t edit my message to include code tags.
    My apologies.

    Moderator bcworkz

    (@bcworkz)

    No worries about code tags. You only have 30 minutes to edit your topic before it’s locked. Coming back and editing topics much later is a spammer trick we try to prevent. I know you’re not a spammer, just explaining the reasoning. I’m sure you’ll make more of an effort with code tags next time ??

    Why wouldn’t you use media_handle_upload()? It’ll move the uploaded file from temp (using wp_handle_upload()) and create an attachment post which relates to the new post you’ve created, including setting appropriate meta data with wp_update_attachment_metadata().

    In other words it does everything you’re trying to do (and failing at) without all the fuss. There are a number of filter and action hooks with which you can modify behavior if the default behavior is unsatisfactory for any reason.

    Thread Starter AndradeL

    (@womday)

    Hi, thank you for the reply.

    Quote ‘Why wouldn’t you use media_handle_upload()?’
    Answer: because wp_insert_attachment actually conntected to the SQL, so I went on with that hook.

    I have managed to get the file to upload and be visible when logged in to ‘wp-admin and click within the menu on Media’ by using your advice, but I’m not there yet.

    
    <?php
    session_start();
    // require '../includes/functions.php';
    require_once '../../../../wp-load.php';
    require_once '../../../../wp-admin/includes/file.php';
    
    // Verplichte requires voor de uploaden
    require_once(  '../../../../wp-admin/includes/image.php' );
    require_once(  '../../../../wp-admin/includes/media.php' );
    
    // END Verplichte requires voor de uploaden
    
    $titel             = $_POST['titel'];
    $selectedOnderwerp = $_POST['selectedOnderwerp'];
    $berichtTextarea   = $_POST['berichtTextarea'];
    $uploadedFileValue = $_FILES['uploadedFileValue'];
    $filename          = $_FILES['uploadedFileValue']["name"];
    $fileType          = $_FILES['uploadedFileValue']["type"];
    
    global $user_ID;
    global $post;
    global $post_id;
    
    $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),
      'post_author' => get_current_user_id(),
    );
    
    //workin post methode
    $post_id = wp_insert_post($new_post);
    
    //The following succesfully ads the image (or PDF) to the SQL, but also to the
    // backend in wp-admin/ media -> (image / attachment visible here)
    // but whatever I do the image / attachment can't be found in posts -> the actual post
    
    $attachment_id = media_handle_upload( 'uploadedFileValue', $post_id );
    
    $wp_upload_dir = wp_upload_dir();
    
    $data = array(
        'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ),
        'post_mime_type' => $fileType,
        'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
        'post_content'   => '',
        'post_status'    => 'inherit'
    );
    
    //attach meta data as instructed to the post
    wp_update_attachment_metadata( $currentPostID, $data );
    

    I have been going for over 48+ hours and would really appreciate if possible, the help, if you could help and or write the final part, so that the image gets into the WordPress post, so I can edit the styling from the WordPress editor when logged in.

    Moderator bcworkz

    (@bcworkz)

    Even media_handle_upload() does not get the image into the post. Only the relationship is established. You can make an image attachment a featured image with set_post_thumbnail(). If the image is to be in post content, you could append or prepend a HTML img tag (or image block) to post content. Or do similarly for other MIME types using appropriate HTML based on type.

    It’s also feasible for a theme to grab attachments and display them via template code, without them being literally within the post. As template code is a poor curator, automatically doing this could yield undesirable results.

    Thread Starter AndradeL

    (@womday)

    So I have started a project which deadline is ending soon.

    The custom theme and everyhting has been setup.
    The only thing that is required, is to have a overview page whichs shows all of the posts made with the attachments.

    Is it correct that I need to seek the attachment by searching for the ‘post ID’, and then retreive it by using SQL?

    Where I then use HTML for the markup?

    QUOTE “If the image is to be in post content, you could append or prepend a HTML img tag (or image block) to post content”

    Is there a page which explains how to summon that content?

    Also, I’d like this feature to be implemented because WordPress already adds an image (or file attachment) to a post in ‘wp-admin/posts’. It’s already happening when a post is made so a hook for it shouldn’t be ‘that’ much of a hassle? Where would I be able to file a feature request sir?

    Moderator bcworkz

    (@bcworkz)

    There are likely WP functions to handle typical queries, it’s rare that you’d need to directly execute your own SQL. The functions will do it for you. You can get media attached to a particular post with get_attached_media(). This would return an array of attachment objects. If you call this for a new post with only one attachment, it’s obvious which attachment to use. It’s less clear for older posts with multiple attachments.

    You can get raw post content from the WP_Post object’s content property. Get the object with get_post(). For a newly inserted post, it’s not going to be any different than what (if any) you initially provided as content. Modify the content as desired, then update the DB with wp_update_post().

    There are already a good number of hooks in the wp_insert_post() function, which is called by wp_update_post(). Review its source code. I’m not sure what what feature you’d be requesting. Anyway, feature requests are manged through our Trac system along with bug reports.
    https://core.trac.www.ads-software.com/newticket

    Thread Starter AndradeL

    (@womday)

    Thank you for your reply. I immediately went trying, hence my lack of immediate response.

    Your post was spot on and I could commit and stick to that, rather then switching between certain hooks, not knowing wether they were to be used or not (just as wp_insert_attachment).

    I have succesfully created a post, by uploading text from my form and by attaching an image by doing a upload (input type=’file’).
    Then I successfully got the image to be added to MEDIA and then to attach it’s ID to the post.

    The following code is just plain, without the security features.

    
    session_start();
    
    Based on my current directory path:
    // 
    require ('../includes/functions.php');
    require_once('../../../../wp-load.php');
    
    // required for uploading
    require_once('../../../../wp-admin/includes/file.php'  );
    require_once('../../../../wp-admin/includes/image.php' );
    require_once('../../../../wp-admin/includes/media.php' );
    
    // END requirements uploaden
    
    //The following $_POSTS are coming from my HTML form
    
    $titel             = $_POST['titel'];
    $selectedOnderwerp = $_POST['selectedOnderwerp'];//subject
    $berichtTextarea   = $_POST['berichtTextarea']; //textarea
    $uploadedFileValue = $_FILES['uploadedFileValue']; //<input type = 'file' name='uploadedFileValue'>
    $filename          = $_FILES['uploadedFileValue']["name"]; //name of the file
    $fileType          = $_FILES['uploadedFileValue']["type"];
    

    Not persé needed

    
    global $user_ID;
    global $post;
    global $post_id;
    
    
    // The data for the post
       $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),
      'post_author'   => get_current_user_id(),
    );
    

    Now create the post

    
    $post_id = wp_insert_post($new_post);
    

    Get the current POST ID

        
    $currentPostID = $post_id;
    
    echo $currentPostID;
    

    And attach the attachmentFile to the post_id

    
    // once more, 'uploadedFileValue' is the name of my input file in html form
    $attachment_id = media_handle_upload( 'uploadedFileValue', $post_id );
    
    // from here I redirect  the user
    header( 'location: ../pages/page-overzicht.php');
    exit;
    

    Then to display that post:

    In have created an attachPost.php with the following content

    
    <?php
    session_start();
      require_once( '../../../../wp-load.php');
    
      // required for gettinng attachments
    
      require_once(  '../../../../wp-includes/post.php'   );
      require_once(  '../../../../wp-includes/plugin.php' );
      require_once(  '../../../../wp-includes/media.php'  );
    

    Then in page-display.php

    
    <?php
      include_once '../pages/attachPost.php';
      $xy = query_posts( 'post_type=post&posts_per_page=10');
    ?>
    

    You can do the styling by yourself, just plain php:

    
    <div class="itemClusterContainer">
      <?php
    
          foreach($xy as $va => $key) :?>
    
            <div class="itemCluster">
                <div>
                    <img src="../img/body/MediaVormgeven-en-Ict.svg" alt="gears">
                </div>
    
                <span class="itemClusterTextClass"><?php echo $key->post_title;?></span>
                <br>
                    <a class="buttonMain" href="../pages/page-article.php?id=<?php echo $key->ID;?>">Bekijk</a>
                <br>
            </div>
    
      <?php endforeach ?>
     </div>
    

    The above was a sumary page, when you click on the actual button you get the data of the post as following on

    page-article.php

    
    <?php
    session_start();
    include_once './attachPost.php';
    
    
    $postIdNumber = $_GET['id'] // from the button you have clicked to come here;
    
    //Get the media
    $mediaArticle = get_attached_media( '', $postIdNumber);
    
    $postIdNumber = get_post( $postIdNumber );
    $title = $postIdNumber->post_title;
    ?>
    

    Show the title

    
    
    <div id="wpBericht" class="itemCluster">
    
                  <?php
                   $postContent = get_post( $postIdNumber );
                   if($postContent)
                     {
                       $title = $postContent->post_content;
                       echo $title;
                       echo '<br><br><br>';
                     }
                    else{
                      echo 'Er is geen bericht aan de post toegevoegd <br><br>';
                    }
    
                  ?>
           </div>
    

    Show the content of the upload, somewhat modified for here

    
    <?php
    
                foreach ($mediaArticle as $articleInfo => $key)
                {
                  if ($key->post_mime_type === 'image/png' || $key->post_mime_type === 'image/jpg' || $key->post_mime_type === 'image/jpeg'){?>
                          <img class="imageSecTwo" src="<?php echo $key->guid; ?>" />
                          <p>
                            <a href="<?php echo $key->guid;?>" download>
                            Download: <u><?php echo $key->post_title;?></u>
                            </a>
                          </p>
                        <?php
                      }
                    else{
                      echo 'This post has no attachment';
                    }
                }
        ?>
    

    I am very happy with your spot on help.
    If this forum allowed me to +rep you I would have done so.

    God bless you @bcworkz

    • This reply was modified 2 years, 5 months ago by AndradeL.
    • This reply was modified 2 years, 5 months ago by AndradeL. Reason: Better markup
    • This reply was modified 2 years, 5 months ago by AndradeL. Reason: + posting the content
    • This reply was modified 2 years, 5 months ago by AndradeL.
    • This reply was modified 2 years, 5 months ago by AndradeL. Reason: More code for completion
    • This reply was modified 2 years, 5 months ago by AndradeL. Reason: Forgot to close the `tag`
    • This reply was modified 2 years, 5 months ago by AndradeL. Reason: Final edit. Deleted code that is not needed for you
    • This reply was modified 2 years, 5 months ago by AndradeL.
    Moderator bcworkz

    (@bcworkz)

    Your pleasure at success makes me happy as well! Thanks for sharing what you came up with, it’ll likely be helpful to others searching for similar solutions.

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘WordPress upload post and attach file (wp_insert_post and wp_insert_attachment)’ is closed to new replies.