Do attachments added to custom post types have a post parent?

After some research, I found that Custom Post Types don’t store post_parent for attachments or may be requires some tweaking with register_post_type().

However, I found that when uploading attachments to regular posts, WordPress sends a post_id with AJAX and same is not happened with Custom Post Types. So, we need to assign post_id to Custom Post Type media uploader. Here is the snippet.

add_filter( 'wp_insert_post', 'foo_insert_post');
function foo_insert_post( $post_id, $post, $update ){
    //if this is cpt, go on
    if( 'your_cpt' === $post->post_type ){
        //ref: wp-includes\media.php @ ~2648
        //ref: https://developer.wordpress.org/reference/hooks/plupload_default_params/
        add_filter( 'plupload_default_params', 'foo_plupload_config');
    }
}

function foo_plupload_config($params){
    global $post;
    //assign current post id
    $params['post_id']      = $post->ID;
    return $params;
}

Hope, it works.

Leave a Comment