post_id missing from the wp-admin file upload request

I'm trying to upload an attachment using the "Add Media" button placed right above the editor.

The request goes to the wp-admin/async-upload.php file. I can put a var_dump($_REQUEST); call there.

Whenever I upload an attachment for a regular post, the $_REQUEST contains the post_id key and the attachment has that post saved as it's parent_post.

But when I do the same for a custom post type I've created, the post_id key is missing. I have no idea why.

Tried adding XHR breakpoints to that upload request, but they all lead to the minified plupload.full.min.js code that seems abstracted from whatever data is being passed through it. I tried searching for the entry point where it starts that upload (and probably has some condition on whether to include the post id) but couldn't find it.

A hidden input with the correct post_id is present on both pages.

When I call media_handle_upload('file', $post_id); from elsewhere in the code, the file gets attached as expected.

Why do the custom post type upload requests omit the post_id? Am I missing something in the post type declaration?

Please help

Topic plupload uploads Wordpress

Category Web


The Sexiest Man in Jamaica's answer is the fix.

For my use I had a custom wp.media instance with a type parameter so that I could hook into uploads and adjust file paths based on type. That or something else I'm doing resulted in post_parent being set to zero for attachments.

At any rate I tweaked things a bit for my own needs:

/**
  * Ensure our custom upload type has a post (parent) ID
  * Without this attachments have a post_parent of 0
  * @since 1.0.0
  */
function plupload_params ($params) {
    global $post;

    if (isset($post) && $post->post_type == 'my_custom_type') {
        $params['post_id'] = $post->ID;
    }

    return $params;
} // End plupload_params()

add_filter('plupload_default_params', 'plupload_params'));

Ok this seems to have fixed it:

function wp_plupload_include_attachment_id( $params ) { 
    global $post_ID; 
    if ( isset( $post_ID ) ) 
        $params['post_id'] = (int) $post_ID; 
    return $params; 
} 
add_filter( 'plupload_default_params', 'wp_plupload_include_attachment_id' ); 

This preprocesses the uploader $params and makes sure the post_id is included.

Taken from here: https://core.trac.wordpress.org/attachment/ticket/22085/media.php.patch

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.