有没有一种方法可以通过上传前端文件来更新Wordpress中的自定义字段? [英] Is there a way to update a custom field in Wordpress with a front-end file upload?
问题描述
我正在尝试使用从前端表单上传的文件来更新自定义WordPress字段.
I am trying to update a custom WordPress-field with a file upload from a front-end form.
示例:
<form action="submit"><input type="file" name="file_upload"><button type="submit">Submit</button></form>
现在,我正在寻找php代码,以更新WordPress中具有特定ID的名为"file_upload"的自定义字段(文件上传).我使用的插件是高级自定义字段".
Now I am looking for the php code that updates the custom field (file upload) in WordPress named 'file_upload' of a post with a certain ID. The plugin I use is 'Advanced Custom Fields'.
我通过PhP中的$ _FILES请求获取文件:
I get the file via an $_FILES request in PhP:
$file_upload = $_FILES['file_upload'];
然后我尝试通过这种方法处理上传:
Then I try to handle the upload via this method:
$file_upload_id = media_handle_upload( $file_upload, 0 );
这是正确的方法吗?
推荐答案
Wordpress具有内置上传功能,该功能返回您需要更新字段的附件ID,建议使用随机数字段来验证其正确位置.
Wordpress has a build in upload function that returns the attachment id you need to update the field, its recommended to use a nonce field to verify it's the right place.
if (
isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
if ( is_wp_error( $attachment_id ) ) {
update_field('image', $attachment_id, $_POST['post_id']);
} else {
// The image was uploaded successfully!
}
} else {
// The security check failed, maybe show the user an error.
}
这篇关于有没有一种方法可以通过上传前端文件来更新Wordpress中的自定义字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!