How can i upload images in an admin page?

时间:2017-10-20 17:36:47

标签: php wordpress

I am trying to upload images in the user profile admin page i have found the function media_handle_upload in the codex here,但有些错误,我会继续error Uploading。我不知道代码中是否缺少某些内容。

我还试图在user-edit页面中使用相同的功能,但我不断收到“无效的用户ID”错误。

function image_up_gall(){
?>
<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="1" />
    <?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.
        echo "error Uploading";
    } else {
        // The image was uploaded successfully!
        echo "Successfully Uploaded";
    }

} else {

    // The security check failed, maybe show the user an error.
    echo "security check error";
}
}
add_action('edit_user_profile', 'image_up_gall');
add_action('show_user_profile', 'image_up_gall');

0 个答案:

没有答案