Hướng dẫn wordpress upload file to media library programmatically - tải tệp wordpress lên thư viện phương tiện theo chương trình

Tôi đang cố gắng lập trình thêm nhiều hình ảnh vào thư viện phương tiện, tôi đã tải hình ảnh lên wp-content/uploads, bây giờ tôi cố gắng sử dụng wp_insert_attachement.

Đây là mã, tuy nhiên nó không hoạt động như mong đợi, tôi nghĩ siêu dữ liệu không được tạo đúng, tôi có thể thấy các tệp trong thư viện phương tiện, nhưng không có hình thu nhỏ, nếu tôi chỉnh sửa hình ảnh tôi gặp lỗi khi tải lại hình ảnh .

$filename_array = array(
   'article1.jpg',
   'article2.jpg',
);

// The ID of the post this attachment is for.
$parent_post_id = 0;

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

foreach ($filename_array as $filename) {

    // Check the type of file. We'll use this as the 'post_mime_type'.
    $filetype = wp_check_filetype( basename( $filename ), null );

    // Prepare an array of post data for the attachment.
    $attachment = array(
        'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
        'post_mime_type' => $filetype['type'],
        'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
        'post_content'   => '',
        'post_status'    => 'inherit'
    );

    // Insert the attachment.
    $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

    // Make sure that this file is included, as   wp_generate_attachment_metadata() depends on it.
    require_once( ABSPATH . 'wp-admin/includes/image.php' );

    // Generate the metadata for the attachment, and update the database record.
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );

}

Cập nhật vào ngày 15 tháng 7 năm 2022

Khi bạn tải các tệp lên trang web của mình bằng trình tải lên phương tiện trong khu vực quản trị, WordPress thường xử lý mọi thứ cho bạn. Vì vậy, tất cả các tệp được tải lên tự động xuất hiện trong thư viện phương tiện WordPress và sau đó có thể dễ dàng quản lý, được chèn vào các bài đăng, v.v.

Nhưng khi bạn tạo một số chức năng tùy chỉnh, hoặc có thể các hình thức trên mặt trước trang web của bạn, bạn nên tự xử lý nó. Và trong hướng dẫn này, tôi sẽ chỉ cho bạn cách.

Hướng dẫn wordpress upload file to media library programmatically - tải tệp wordpress lên thư viện phương tiện theo chương trình
Việc tổ chức các hình ảnh đã tải lên của bạn bằng thư viện truyền thông WordPress là dễ dàng hơn. Ảnh của tôi.

Trong hướng dẫn này, chúng tôi sẽ xem xét hai kịch bản:

  1. Khi tải lên hình ảnh từ URL (tất nhiên không chỉ hình ảnh),
  2. Khi tải lên các tập tin bằng một biểu mẫu.

Tải lên hình ảnh từ URL lập trình

Hãy bắt đầu với một hình ảnh ở bất cứ đâu trên internet. Giả sử rằng chúng tôi có URL của nó, và bây giờ nó được lưu trữ trong biến $image_url. Làm thế nào để thêm nó vào thư viện phương tiện ngay bây giờ?

/**
 * Upload image from URL programmatically
 *
 * @author Misha Rudrastyh
 * @link https://rudrastyh.com/wordpress/how-to-add-images-to-media-library-from-uploaded-files-programmatically.html#upload-image-from-url
 */
function rudr_upload_file_by_url( $image_url ) {

	// it allows us to use download_url() and wp_handle_sideload() functions
	require_once( ABSPATH . 'wp-admin/includes/file.php' );

	// download to temp dir
	$temp_file = download_url( $image_url );

	if( is_wp_error( $temp_file ) ) {
		return false;
	}

	// move the temp file into the uploads directory
	$file = array(
		'name'     => basename( $image_url ),
		'type'     => mime_content_type( $temp_file ),
		'tmp_name' => $temp_file,
		'size'     => filesize( $temp_file ),
	);
	$sideload = wp_handle_sideload(
		$file,
		array(
			'test_form'   => false // no needs to check 'action' parameter
		)
	);

	if( ! empty( $sideload[ 'error' ] ) ) {
		// you may return error message if you want
		return false;
	}

	// it is time to add our uploaded image into WordPress media library
	$attachment_id = wp_insert_attachment(
		array(
			'guid'           => $sideload[ 'url' ],
			'post_mime_type' => $sideload[ 'type' ],
			'post_title'     => basename( $sideload[ 'file' ] ),
			'post_content'   => '',
			'post_status'    => 'inherit',
		),
		$sideload[ 'file' ]
	);

	if( is_wp_error( $attachment_id ) || ! $attachment_id ) {
		return false;
	}

	// update medatata, regenerate image sizes
	require_once( ABSPATH . 'wp-admin/includes/image.php' );

	wp_update_attachment_metadata(
		$attachment_id,
		wp_generate_attachment_metadata( $attachment_id, $sideload[ 'file' ] )
	);

	return $attachment_id;

}

Tải lên các tệp trong PHP bằng các biểu mẫu

Phần này của hướng dẫn là loại tương tự, sự khác biệt duy nhất là chúng tôi sẽ không lấy tệp từ một URL từ xa, nhưng tự mình tải lên.

1. Hình thức HTML

Như một ví dụ, chúng tôi có thể tải lên hình ảnh hồ sơ người dùng.

Your Photo:

Điều gì được khuyến khích nhớ ở đây?

  • Tôi đã đặt tệp PHP process_upload.php vào thư mục chủ đề của mình, nếu bạn muốn chuyển nó sang vị trí khác, đừng quên thay đổi các mã sau. Nếu bạn quan tâm đến tải lên tệp AJAX, vui lòng kiểm tra hướng dẫn này.
  • Biểu mẫu phải có thuộc tính enctype="multipart/form-data". Nhiều người quên nó.

Bạn cũng có thể tạo một mã ngắn cho biểu mẫu này, chỉ cần chèn nó vào

/**
 * Upload image from URL programmatically
 *
 * @author Misha Rudrastyh
 * @link https://rudrastyh.com/wordpress/how-to-add-images-to-media-library-from-uploaded-files-programmatically.html#upload-image-from-url
 */
function rudr_upload_file_by_url( $image_url ) {

	// it allows us to use download_url() and wp_handle_sideload() functions
	require_once( ABSPATH . 'wp-admin/includes/file.php' );

	// download to temp dir
	$temp_file = download_url( $image_url );

	if( is_wp_error( $temp_file ) ) {
		return false;
	}

	// move the temp file into the uploads directory
	$file = array(
		'name'     => basename( $image_url ),
		'type'     => mime_content_type( $temp_file ),
		'tmp_name' => $temp_file,
		'size'     => filesize( $temp_file ),
	);
	$sideload = wp_handle_sideload(
		$file,
		array(
			'test_form'   => false // no needs to check 'action' parameter
		)
	);

	if( ! empty( $sideload[ 'error' ] ) ) {
		// you may return error message if you want
		return false;
	}

	// it is time to add our uploaded image into WordPress media library
	$attachment_id = wp_insert_attachment(
		array(
			'guid'           => $sideload[ 'url' ],
			'post_mime_type' => $sideload[ 'type' ],
			'post_title'     => basename( $sideload[ 'file' ] ),
			'post_content'   => '',
			'post_status'    => 'inherit',
		),
		$sideload[ 'file' ]
	);

	if( is_wp_error( $attachment_id ) || ! $attachment_id ) {
		return false;
	}

	// update medatata, regenerate image sizes
	require_once( ABSPATH . 'wp-admin/includes/image.php' );

	wp_update_attachment_metadata(
		$attachment_id,
		wp_generate_attachment_metadata( $attachment_id, $sideload[ 'file' ] )
	);

	return $attachment_id;

}
0:

add_shortcode( 'misha_uploader', 'misha_uploader_callback' );

function misha_uploader_callback(){
	return '
Your Photo:
'; }

Bây giờ bạn có thể chỉ sử dụng

/**
 * Upload image from URL programmatically
 *
 * @author Misha Rudrastyh
 * @link https://rudrastyh.com/wordpress/how-to-add-images-to-media-library-from-uploaded-files-programmatically.html#upload-image-from-url
 */
function rudr_upload_file_by_url( $image_url ) {

	// it allows us to use download_url() and wp_handle_sideload() functions
	require_once( ABSPATH . 'wp-admin/includes/file.php' );

	// download to temp dir
	$temp_file = download_url( $image_url );

	if( is_wp_error( $temp_file ) ) {
		return false;
	}

	// move the temp file into the uploads directory
	$file = array(
		'name'     => basename( $image_url ),
		'type'     => mime_content_type( $temp_file ),
		'tmp_name' => $temp_file,
		'size'     => filesize( $temp_file ),
	);
	$sideload = wp_handle_sideload(
		$file,
		array(
			'test_form'   => false // no needs to check 'action' parameter
		)
	);

	if( ! empty( $sideload[ 'error' ] ) ) {
		// you may return error message if you want
		return false;
	}

	// it is time to add our uploaded image into WordPress media library
	$attachment_id = wp_insert_attachment(
		array(
			'guid'           => $sideload[ 'url' ],
			'post_mime_type' => $sideload[ 'type' ],
			'post_title'     => basename( $sideload[ 'file' ] ),
			'post_content'   => '',
			'post_status'    => 'inherit',
		),
		$sideload[ 'file' ]
	);

	if( is_wp_error( $attachment_id ) || ! $attachment_id ) {
		return false;
	}

	// update medatata, regenerate image sizes
	require_once( ABSPATH . 'wp-admin/includes/image.php' );

	wp_update_attachment_metadata(
		$attachment_id,
		wp_generate_attachment_metadata( $attachment_id, $sideload[ 'file' ] )
	);

	return $attachment_id;

}
1 trong trình soạn thảo.

2. Xử lý tệp đã tải lên trong PHP và thêm nó vào thư viện phương tiện theo chương trình

Dưới đây là tệp process_upload.php mà tôi quyết định tạo trong thư mục chủ đề hiện tại của mình.

 false ) 
);

if( ! empty( $upload[ 'error' ] ) ) {
	wp_die( $upload[ 'error' ] );
}

// it is time to add our uploaded image into WordPress media library
$attachment_id = wp_insert_attachment(
	array(
		'guid'           => $upload[ 'url' ],
		'post_mime_type' => $upload[ 'type' ],
		'post_title'     => basename( $upload[ 'file' ] ),
		'post_content'   => '',
		'post_status'    => 'inherit',
	),
	$upload[ 'file' ]
);

if( is_wp_error( $attachment_id ) || ! $attachment_id ) {
	wp_die( 'Upload error.' );
}

// update medatata, regenerate image sizes
require_once( ABSPATH . 'wp-admin/includes/image.php' );

wp_update_attachment_metadata(
	$attachment_id,
	wp_generate_attachment_metadata( $attachment_id, $upload[ 'file' ] )
);

// just redirect to the uploaded file
wp_safe_redirect( $upload[ 'url' ] );
exit;

// or you can use update_user_meta() if you're going ot use it as a profile picture

Tùy chọn, chúng tôi có thể đặt tham số thứ ba của

/**
 * Upload image from URL programmatically
 *
 * @author Misha Rudrastyh
 * @link https://rudrastyh.com/wordpress/how-to-add-images-to-media-library-from-uploaded-files-programmatically.html#upload-image-from-url
 */
function rudr_upload_file_by_url( $image_url ) {

	// it allows us to use download_url() and wp_handle_sideload() functions
	require_once( ABSPATH . 'wp-admin/includes/file.php' );

	// download to temp dir
	$temp_file = download_url( $image_url );

	if( is_wp_error( $temp_file ) ) {
		return false;
	}

	// move the temp file into the uploads directory
	$file = array(
		'name'     => basename( $image_url ),
		'type'     => mime_content_type( $temp_file ),
		'tmp_name' => $temp_file,
		'size'     => filesize( $temp_file ),
	);
	$sideload = wp_handle_sideload(
		$file,
		array(
			'test_form'   => false // no needs to check 'action' parameter
		)
	);

	if( ! empty( $sideload[ 'error' ] ) ) {
		// you may return error message if you want
		return false;
	}

	// it is time to add our uploaded image into WordPress media library
	$attachment_id = wp_insert_attachment(
		array(
			'guid'           => $sideload[ 'url' ],
			'post_mime_type' => $sideload[ 'type' ],
			'post_title'     => basename( $sideload[ 'file' ] ),
			'post_content'   => '',
			'post_status'    => 'inherit',
		),
		$sideload[ 'file' ]
	);

	if( is_wp_error( $attachment_id ) || ! $attachment_id ) {
		return false;
	}

	// update medatata, regenerate image sizes
	require_once( ABSPATH . 'wp-admin/includes/image.php' );

	wp_update_attachment_metadata(
		$attachment_id,
		wp_generate_attachment_metadata( $attachment_id, $sideload[ 'file' ] )
	);

	return $attachment_id;

}
3 làm ID bài viết mẹ và đặt hình ảnh đặc trưng của bài đăng này với
/**
 * Upload image from URL programmatically
 *
 * @author Misha Rudrastyh
 * @link https://rudrastyh.com/wordpress/how-to-add-images-to-media-library-from-uploaded-files-programmatically.html#upload-image-from-url
 */
function rudr_upload_file_by_url( $image_url ) {

	// it allows us to use download_url() and wp_handle_sideload() functions
	require_once( ABSPATH . 'wp-admin/includes/file.php' );

	// download to temp dir
	$temp_file = download_url( $image_url );

	if( is_wp_error( $temp_file ) ) {
		return false;
	}

	// move the temp file into the uploads directory
	$file = array(
		'name'     => basename( $image_url ),
		'type'     => mime_content_type( $temp_file ),
		'tmp_name' => $temp_file,
		'size'     => filesize( $temp_file ),
	);
	$sideload = wp_handle_sideload(
		$file,
		array(
			'test_form'   => false // no needs to check 'action' parameter
		)
	);

	if( ! empty( $sideload[ 'error' ] ) ) {
		// you may return error message if you want
		return false;
	}

	// it is time to add our uploaded image into WordPress media library
	$attachment_id = wp_insert_attachment(
		array(
			'guid'           => $sideload[ 'url' ],
			'post_mime_type' => $sideload[ 'type' ],
			'post_title'     => basename( $sideload[ 'file' ] ),
			'post_content'   => '',
			'post_status'    => 'inherit',
		),
		$sideload[ 'file' ]
	);

	if( is_wp_error( $attachment_id ) || ! $attachment_id ) {
		return false;
	}

	// update medatata, regenerate image sizes
	require_once( ABSPATH . 'wp-admin/includes/image.php' );

	wp_update_attachment_metadata(
		$attachment_id,
		wp_generate_attachment_metadata( $attachment_id, $sideload[ 'file' ] )
	);

	return $attachment_id;

}
4.

#& nbsp; WordPress, tệp đính kèm

Hướng dẫn wordpress upload file to media library programmatically - tải tệp wordpress lên thư viện phương tiện theo chương trình

Misha Rudrastyh

Này các bạn và chào mừng bạn đến với trang web của tôi. Trong hơn 10 năm, tôi đã cố gắng hết sức để chia sẻ với bạn một số hướng dẫn và mẹo tuyệt vời của WordPress miễn phí.

Cần một số nhà phát triển giúp đỡ? Liên hệ với tôi

Theo dõi tôi trên Twitter

Làm thế nào có thể tải lên phương tiện truyền thông trong WordPress?

Cách tải lên các tập tin trong chương trình WordPress..
Bước 1: Tạo tệp plugin. ....
Bước 2: Tạo một chức năng sẽ hiển thị trình tải lên tệp. ....
Bước 3: Thêm hàm để hiển thị biểu mẫu của chúng tôi. ....
Bước 4: Thêm một móc cho mã ngắn để hoạt động. ....
Bước 5: Thêm mã PHP để xử lý biểu mẫu của chúng tôi ..

Làm cách nào để thêm các tệp vào thư viện phương tiện WordPress?

Sau khi bạn đã cài đặt plugin, trong bảng điều khiển WordPress của mình, hãy chuyển đến phương tiện menu bên trái -> Thêm từ máy chủ, điều hướng đến thư mục nơi bạn đã tải lên các tệp phương tiện của mình, chọn tệp và nhấp vào nút "Nhập", các tệp phương tiện Sau đó sẽ được nhập vào thư viện phương tiện WordPress của bạn.go to the left menu Media -> Add From Server, navigate to the folder where you have uploaded your media files, select the files and click the "Import" button, the media files will then be imported to your WordPress Media Library.

Làm cách nào để thêm hình ảnh vào thư viện phương tiện WordPress của tôi?

Cách tải lên .jpg, .gif, .png và .pdf:..
Đăng nhập vào trang web WordPress của bạn ..
Nhấp vào phương tiện (điều hướng bên trái)> Thêm mới. ....
Một trong hai: ... .
(Tùy chọn) Bây giờ bạn có thể chỉnh sửa hình ảnh bằng cách nhấp vào nút 'Chỉnh sửa hình ảnh' ..
Điền vào trường văn bản thay thế. ....
Hãy lưu ý URL tệp. ....
Nhấp vào 'Lưu tất cả các thay đổi' để giữ tệp của bạn trong hệ thống ..

Làm cách nào để tạo biểu mẫu tải lên tùy chỉnh trong WordPress?

Cách tạo biểu mẫu tải lên tệp trong WordPress [Hướng dẫn đầy đủ]..
Bước 1: Cài đặt WPForms trên trang web WordPress của bạn ..
Bước 2: Thêm biểu mẫu mới bằng WPForms ..
Bước 3: Tùy chỉnh biểu mẫu tải lên tệp WordPress ..
Bước 4: Định cấu hình Thông báo tải lên tệp WordPress của bạn ..
Bước 5: Định cấu hình xác nhận biểu mẫu tải lên tệp của bạn ..