I need to hook after file uploaded to server, get the file path, and then prevent WordPress from saving the attachment post.

I found this filter add_filter('attachment_fields_to_save', 'attachment_stuff'); but this is after the attachment post was created, I want to hook before the post save.

Update 26.03.2018

I ended up using a custom media endpoint to save the files without saving a attachment post. Full example below in answer

3 Answers
3

Based on your comment you appear to be using the REST API. There’s no hook between uploading the file and creating the attachment post that could be used for this purpose in the API endpoint.

The best you can do appears to be to use the rest_insert_attachment action. It provides callback functions with the WP_Post object for the attachment post, and the WP_REST_Request object representing the request. This action is called immediately after the attachment post is created, but before any metadata or sizes are generated. So you would hook into here, check the request for whatever flag you are using to identify media that shouldn’t get saved as a post, get the path, then delete the attachment post.

function wpse_297026_rest_insert_attachment( $attachment, $request, $creating ) {
    // Only handle new attachments.
    if ( ! $creating ) {
        return;
    }

    // Check for parameter on request that tells us not to create an attachment post.
    if ( $request->get_param( 'flag' ) == true ) {
        // Get file path.
        $file = get_attached_file( $attachment->ID );

        // Do whatever you need to with the file path.

        // Delete attachment post.
        wp_delete_post( $attachment->ID );

        // Kill the request and send a 201 response.
        wp_die('', '', 201);
    }
}
add_action( 'rest_insert_attachment', 'wpse_297026_rest_insert_attachment' )

I think it needs to be pointed out that if you’re not creating attachments then you shouldn’t be using the attachment endpoint. This is why we have to awkwardly kill the request in that code. Everything after rest_insert_attachment assumes the existence of an attachment post and most of the code for the controller for that endpoint is dedicated to creating and managing data that only makes sense for an attachment post. You should probably be creating your own endpoint for this sort of work.

Leave a Reply

Your email address will not be published. Required fields are marked *