media_handle_upload example

check_admin_referer( 'media-form' );

$post_id = 0;
if ( isset( $_REQUEST['post_id'] ) ) {
    $post_id = absint( $_REQUEST['post_id'] );
    if ( ! get_post( $post_id ) || ! current_user_can( 'edit_post', $post_id ) ) {
        $post_id = 0;
    }
}

$id = media_handle_upload( 'async-upload', $post_id );
if ( is_wp_error( $id ) ) {
    printf(
        '<div class="error-div error">%s <strong>%s</strong><br />%s</div>',
        sprintf(
            '<button type="button" class="dismiss button-link" onclick="jQuery(this).parents(\'div.media-item\').slideUp(200, function(){jQuery(this).remove();});">%s</button>',
            __( 'Dismiss' )
        ),
        sprintf(
            /* translators: %s: Name of the file that failed to upload. */
            __( '&#8220;%s&#8221; has failed to upload.' ),
            esc_html( $_FILES['async-upload']['name'] )
        ),

function wp_media_upload_handler() {
    $errors = array();
    $id     = 0;

    if ( isset( $_POST['html-upload'] ) && ! empty( $_FILES ) ) {
        check_admin_referer( 'media-form' );
        // Upload File button was clicked.         $id = media_handle_upload( 'async-upload', $_REQUEST['post_id'] );
        unset( $_FILES );

        if ( is_wp_error( $id ) ) {
            $errors['upload_error'] = $id;
            $id                     = false;
        }
    }

    if ( ! empty( $_POST['insertonlybutton'] ) ) {
        $src = $_POST['src'];

        
'data'    => array(
                        'message'  => __( 'The uploaded file is not a valid image. Please try again.' ),
                        'filename' => esc_html( $_FILES['async-upload']['name'] ),
                    ),
                )
            );

            wp_die();
        }
    }

    $attachment_id = media_handle_upload( 'async-upload', $post_id$post_data );

    if ( is_wp_error( $attachment_id ) ) {
        echo wp_json_encode(
            array(
                'success' => false,
                'data'    => array(
                    'message'  => $attachment_id->get_error_message(),
                    'filename' => esc_html( $_FILES['async-upload']['name'] ),
                ),
            )
        );

        
if ( isset( $_REQUEST['post_id'] ) ) {
    $post_id = absint( $_REQUEST['post_id'] );
    if ( ! get_post( $post_id ) || ! current_user_can( 'edit_post', $post_id ) ) {
        $post_id = 0;
    }
}

if ( $_POST ) {
    if ( isset( $_POST['html-upload'] ) && ! empty( $_FILES ) ) {
        check_admin_referer( 'media-form' );
        // Upload File button was clicked.         $upload_id = media_handle_upload( 'async-upload', $post_id );
        if ( is_wp_error( $upload_id ) ) {
            wp_die( $upload_id );
        }
    }
    wp_redirect( admin_url( 'upload.php' ) );
    exit;
}

// Used in the HTML title tag. $title       = __( 'Upload New Media' );
$parent_file = 'upload.php';

Home | Imprint | This part of the site doesn't use cookies.