我需要挂接上传到服务器的文件,获取文件路径,然后阻止WordPress保存附件post。
我找到了这个过滤器add_filter('attachment_fields_to_save', 'attachment_stuff');
,但是这是在创建了附件post之后,我想在post保存之前挂钩。
Update 26.03.2018
最后,我使用了一个自定义媒体端点来保存文件,而不保存附件帖子。下面是回答中的完整示例
发布于 2018-03-16 16:24:10
根据您的评论,您似乎在使用REST。上传文件与在API端点中创建可用于此目的的附件post之间没有挂钩。
最好的方法似乎是使用rest_insert_attachment
操作。它提供带有附件post的WP_Post
对象和代表请求的WP_REST_Request
对象的回调函数。此操作在创建附件后立即调用,但在生成任何元数据或大小之前调用。因此,您可以挂在这里,检查请求,检查用于标识不应该保存为post的媒体的请求,获取路径,然后删除附件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' )
我认为需要指出的是,如果您没有创建附件,那么就不应该使用附件端点。这就是为什么我们不得不在代码中笨拙地删除请求的原因。rest_insert_attachment
之后的一切都假设存在一个附件post,并且该端点的控制器的大部分代码都专门用于创建和管理仅对附件post有意义的数据。您可能应该为这类工作创建自己的端点。
发布于 2018-03-16 16:04:33
上传文件并为其创建附件由函数media_handle_upload
处理。从源代码中可以看到,它首先上载文件,然后开始收集元数据(包括一些用于音频文件的冗长内容),然后调用wp_insert_attachment
创建附件post。没有地方能让你上钩。
后一个函数只是wp_insert_post
的占位符。在这里,您有相当多的钩子来过滤元数据。然而,只有一个条件可以阻止创建帖子,上面写着if ( ! empty( $import_id ) )
。而且也没有明显的方法来搅乱$import_id
。所以你被困住了。
除了函数后面的部分,还有一个调用:do_action( 'add_attachment', $post_ID );
。这是在创建了一个附件后才触发的。您可以使用它再次删除该帖子:
add_action ('add_attachment', 'wpse297026_delete_post');
function wpse297026_delete_post ($post_ID) {
wp_delete_post ($post_ID);
}
这将使上传的文件处于其位置,但WordPress将失去对它的跟踪。
发布于 2018-03-26 20:55:48
最后,我在自定义端点中使用了来自wp媒体端点的代码,而没有保存post部分。
这里是关于二十七个孩子主题的完整例子,以防有人需要这个。
$\_FILES
超级全局。* @param数组$headers headers来自请求。**@从array|WP_Error ()返回wp_handle_upload数据。*/受保护的函数upload_from_file( $files,$headers ){ if (空( $files )){返回新的WP_Error(‘rest_rest_No_ data’),__( 'No data提供的‘),数组( 'status’=> 400 );}/验证哈希(如果给定的话)。如果(!空( $headers ) ){ $content_md5 = array_shift( $headers );$expected = trim( $content_md5 );$actual = md5_file( $files );if ( $expected !== $actual ){返回新WP_Error(‘rest_upload_ hash _失配’)、__(‘内容哈希不匹配预期。’)、数组( 'status‘=> 412 );} //传递到WP以处理实际上载。当运行单元测试时,$overrides = => ( 'test_form‘=> false );//旁路is_uploaded_file()。如果(定义为( ' DIR_TESTDATA‘) && DIR_TESTDATA){ $overrides =’wp_$overrides_mock_$overrides‘} /**包含管理函数,以获得对wp_handle_upload() */ require_once ABSPATH的访问。‘’wp admin/include/admin.php‘;$file = wp_handle_upload( $files,$overrides );if ( isset( $file )){返回新的WP_Error(’rest_upload_error_error‘,$file,数组( 'status’=> 500 );}返回$file;}}确保您登录并将permalinks设置为post名称,以允许端点运行。
https://wordpress.stackexchange.com/questions/297026
复制相似问题