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.

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 //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.

Bài Viết Liên Quan

Chủ Đề