我正在制作Wordpress插件,它将图像作为输入。我需要为用户提供添加和删除图像的界面。哪个是提供此界面的最佳选择?
答案 0 :(得分:0)
我认为media_handle_upload()
正是您所寻找的。此WordPress函数处理文件上载/ POST请求,并在数据库中创建附件发布。 WordPress Codex中的Here is the full documentation。
您可以使用此界面创建一个界面,允许用户通过表单从前端上传图像。
以下是他们目前在Codex中为media_handle_upload
提供的官方示例(如果链接在将来发生变化,请在此处重新发布):
上传表单(示例):
<form id="featured_upload" method="post" action="#" enctype="multipart/form-data">
<input type="file" name="my_image_upload" id="my_image_upload" multiple="false" />
<input type="hidden" name="post_id" id="post_id" value="55" />
<?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>
<input id="submit_my_image_upload" name="submit_my_image_upload" type="submit" value="Upload" />
</form>
保存附件(示例):
<?php
// Check that the nonce is valid, and the user can edit this post.
if (
isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
&& current_user_can( 'edit_post', $_POST['post_id'] )
) {
// The nonce was valid and the user has the capabilities, it is safe to continue.
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Let WordPress handle the upload.
// Remember, 'my_image_upload' is the name of our file input in our form above.
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
} else {
// The image was uploaded successfully!
}
} else {
// The security check failed, maybe show the user an error.
}
要让用户删除上传的图片,您可以使用插件所需的功能wp_delete_attachment
。 (Full Documentation here)。
这使您可以按ID删除特定媒体附件。以下是食典委的例子:
<?php wp_delete_attachment( 76 ); ?>
根据您的需求,我还建议您浏览Related "Attachments" functions in the Codex,因为您可能也想在插件中使用其中的一些。