uploads – Do custom post type (CPT) attachments/media store the parent post ID?

Question

Do custom post type attachments store the parent post ID, and if so, how do I retrieve it.

I am using a form which allows registered users to create a CPT (‘Paper’) and upload a pdf or Word document (via an ACF upload field).

All this is working fine, and the documents are being saved in a custom folder in wp_content/uploads/papers

However, I need to prepend the ID of the created CPT post to the uploaded file name, eg 123-my-file-name.pdf

I do have this question posted on WordPress.org forum and someone is kindly helping me there, but first I need to establish that what I’m doing is actually possible in WordPress. I’m amazed I haven’t found any snippet for this.

For those interested, this is my current code in functions.php which results in nothing being added to the front of the file name.

add_filter( 'wp_handle_upload_prefilter', 'custom_upload_filter' );
function custom_upload_filter($file) {


   // Get the parent post ID, if there is one
       if( isset($_REQUEST['p']) ) {
           $post_id = $_REQUEST['p'];
      } else {
         $post_id = false;
       }
        
    $file['name'] = $post_id . '-' . $file['name'];
    return $file;
}

I’m sorry if I’m breaking protocol by posting here as well. But if I can establish that getting the CPT post id is possible at the point of creating the post and uploading file I can at least continue trying to get the code to work.

Cheers,
Tracy

0
Tracy Shorrock 4 weeks 2021-09-22T18:34:26-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse