wp insert attachment from form input type file, media phần 2 (ok)

Tạo form input ở trong trang signle

add_action('woocommerce_before_add_to_cart_button','fc_woocommerce_before_add_to_cart_button_img');
function fc_woocommerce_before_add_to_cart_button_img() {
    $html = "";
    $html .= '<label class="title" for="imgct">Chọn ảnh:</label>';
    $html .= '<input type="file" id="imgct" name="imgct" style="margin-bottom: 10px;" accept="image/*">';
    echo $html;
}

Xử lý file

add_action('woocommerce_add_to_cart', 'product_option_add_to_cart');
function product_option_add_to_cart() {
    if(isset($_POST['add-to-cart'])) {
    require( dirname(__FILE__) . '/../../../wp-load.php' );
    $wordpress_upload_dir = wp_upload_dir();
    $i = 1; 
    $imgct = $_FILES['imgct'];
    $new_file_path = $wordpress_upload_dir['path'] . '/' . $imgct['name'];
    $new_file_mime = mime_content_type( $imgct['tmp_name'] );
    if( empty( $imgct ) )
        die( 'File is not selected.' );
    if( $imgct['error'] )
        die( $imgct['error'] );
    if( $imgct['size'] > wp_max_upload_size() )
        die( 'It is too large than expected.' );
    if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
        die( 'WordPress doesn\'t allow this type of uploads.' );
    while( file_exists( $new_file_path ) ) {
        $i++;
        $new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $imgct['name'];
    }
    // looks like everything is OK
    if( move_uploaded_file( $imgct['tmp_name'], $new_file_path ) ) {
        $upload_id = wp_insert_attachment( array(
            'guid'           => $new_file_path, 
            'post_mime_type' => $new_file_mime,
            'post_title'     => preg_replace( '/\.[^.]+$/', '', $imgct['name'] ),
            'post_content'   => '',
            'post_status'    => 'inherit'
        ), $new_file_path );
        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        // Generate and save the attachment metas into the database
        wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );
        // Show the uploaded file in browser
        update_post_meta($_POST['add-to-cart'], '_imgct_data', $wordpress_upload_dir['url'] . '/' . basename( $new_file_path ));
        }
    }
}

Kết quả:

Last updated