Bootstrap Skip to main content
Use code LAMVT for an extra 10% off!

From the Firehose

5/5 - (1 bình chọn)

Cách thêm trường tải ảnh trực tiếp vào bảng tùy chỉnh trên website

Bảng tùy chỉnh trong trang quản trị website sẽ có rất nhiều trường mục mà bạn cần phải nắm rõ. Việc làm sao để có thể thêm trường tải ảnh trực tiếp trong trang mà không ảnh hưởng đến cấu hình là điều quan trọng.

Nếu bạn đang cần một hướng dẫn chi tiết về cách thêm trường tải ảnh trực tiếp trong bảng tùy chỉnh quản trị, bạn có thể tham khảo thông tin trong bài viết dưới đây:

Cách thêm trường Tải ảnh vào WordPress upload-file-wordpress

Hiện tại, có ít nhất 3 cách thêm trường tải ảnh vào bài đăng, bao gồm: sử dụng post_meta để lưu trữ đường dẫn hình ảnh; Sử dụng trường post_meta để lưu trữ ID thư viện ảnh hoặc chỉ định hình ảnh cho bài đăng dưới dạng tệp tin đính kèm. Bài viết dưới đây sẽ hướng dẫn bạn cách sử dụng trường post_meta để lưu ID thư viện ảnh.

Xem thêm: Cách hiển thị bài viết xem nhiều nhất trong WordPress không sử dụng Plugin

Mã hóa nhiều phần

Trong WordPress đã mặc định tạo và chỉnh sửa ảnh thường không có thuộc tính enctype. Nếu bạn muốn tải lên một tệp tin, bạn sẽ cần bổ sung “enctype = ‘nhiều phần/mẫu dữ liệu’ vào thẻ biểu mẫu – nếu không bộ sưu tập $_File sẽ không được đẩy qua.


function lamvt_add_edit_form_multipart_encoding() {

echo ' enctype="multipart/form-data"';

}
add_action('post_edit_form_tag', 'lamvt_add_edit_form_multipart_encoding');

Tạo hộp Meta Box và tải lên

Điều cần thiết để tạo trường tải ảnh vào bài đăng là bạn cần thiết lập một hộp meta đơn giản với một trường tệp tin trong đó.
Xử lý tệp tải lên

Đây là một vấn đề lớn, bạn cần xử lý các tệp tin tải lên bằng cách hooking vào hoạt động save_post. Nhưng bạn nên lưu ý tới hai chức năng chính sẽ sử dụng:

– Wp_handle_upload: Đây là chức năng chính giúp xử lý hình ảnh tải lên. Để cài đặt chức năng này hoạt động được tốt nhất, bạn cần đặt là test_form = false và thỏa mãn được tham chiếu đến trường mà bạn xây dựng trong $_FILES. Tuy nhiên, chức năng này không thêm được tệp đã tải lên vào thư viện ảnh.  Nó chỉ đơn giản là tải lên và trả lại đường dẫn tập tin mới cho quản trị viên.  Nếu có vấn đề, nó sẽ trả về thông báo lỗi cho bạn ngay tức thì.


function lamvt_render_image_attachment_box($post) {

// See if there's an existing image. (We're associating images with posts by saving the image's 'attachment id' as a post meta value)
 // Incidentally, this is also how you'd find any uploaded files for display on the frontend.
 $existing_image_id = get_post_meta($post->ID,'_lamvt_attached_image', true);
 if(is_numeric($existing_image_id)) {

echo '<div>';
 $arr_existing_image = wp_get_attachment_image_src($existing_image_id, 'large');
 $existing_image_url = $arr_existing_image[0];
 echo '<img src="' . $existing_image_url . '" />';
 echo '</div>';

}

// If there is an existing image, show it
 if($existing_image_id) {

echo '<div>Attached Image ID: ' . $existing_image_id . '</div>';

}

echo 'Upload an image: <input type="file" name="lamvt_image" id="lamvt_image" />';

// See if there's a status message to display (we're using this to show errors during the upload process, though we should probably be using the WP_error class)
 $status_message = get_post_meta($post->ID,'_lamvt_attached_image_upload_feedback', true);

// Show an error message if there is one
 if($status_message) {

echo '<div class="upload_status_message">';
 echo $status_message;
 echo '</div>';

}

// Put in a hidden flag. This helps differentiate between manual saves and auto-saves (in auto-saves, the file wouldn't be passed).
 echo '<input type="hidden" name="lamvt_manual_save_flag" value="true" />';

}

function lamvt_setup_meta_boxes() {

// Add the box to a particular custom content type page
 add_meta_box('lamvt_image_box', 'Upload Image', 'lamvt_render_image_attachment_box', 'post', 'normal', 'high');

}
add_action('admin_init','lamvt_setup_meta_boxes');

– Wp_insert_attachment:  Đây là chức năng thêm hình ảnh vào thư viện phương tiện và tạo ra tất cả các hình thu nhỏ phù hợp.  Bạn chỉ cần vượt qua một mảng các tùy chọn (tiêu đề, trạng thái bài đăng, v.v.) và đường dẫn LOCAL (không phải URL) tới tệp bạn vừa tải lên.  Chức năng này cho phép bạn có thể dễ dàng xóa tất cả các tệp đã tải lên bằng cách gọi wp_delete_attachment và truyền ID thư viện phương tiện của mục đó.  Với chức năng này, bạn cũng cần phải sử dụng wp_generate_attachment_metadata và wp_update_attachment_metadata, mà thực hiện chính xác những gì bạn mong đợi họ tạo siêu dữ liệu cho mục media.


function lamvt_update_post($post_id, $post) {

// Get the post type. Since this function will run for ALL post saves (no matter what post type), we need to know this.
// It's also important to note that the save_post action can runs multiple times on every post save, so you need to check and make sure the
// post type in the passed object isn't "revision"
$post_type = $post->post_type;

// Make sure our flag is in there, otherwise it's an autosave and we should bail.
if($post_id && isset($_POST['lamvt_manual_save_flag'])) {

// Logic to handle specific post types
switch($post_type) {

// If this is a post. You can change this case to reflect your custom post slug
case 'post':

// HANDLE THE FILE UPLOAD

// If the upload field has a file in it
if(isset($_FILES['lamvt_image']) && ($_FILES['lamvt_image']['size'] > 0)) {

// Get the type of the uploaded file. This is returned as "type/extension"
$arr_file_type = wp_check_filetype(basename($_FILES['lamvt_image']['name']));
$uploaded_file_type = $arr_file_type['type'];

// Set an array containing a list of acceptable formats
$allowed_file_types = array('image/jpg','image/jpeg','image/gif','image/png');

// If the uploaded file is the right format
if(in_array($uploaded_file_type, $allowed_file_types)) {

// Options array for the wp_handle_upload function. 'test_upload' => false
$upload_overrides = array( 'test_form' => false );

// Handle the upload using WP's wp_handle_upload function. Takes the posted file and an options array
$uploaded_file = wp_handle_upload($_FILES['lamvt_image'], $upload_overrides);

// If the wp_handle_upload call returned a local path for the image
if(isset($uploaded_file['file'])) {

// The wp_insert_attachment function needs the literal system path, which was passed back from wp_handle_upload
$file_name_and_location = $uploaded_file['file'];

// Generate a title for the image that'll be used in the media library
$file_title_for_media_library = 'your title here';

// Set up options array to add this file as an attachment
$attachment = array(
'post_mime_type' => $uploaded_file_type,
'post_title' => 'Uploaded image ' . addslashes($file_title_for_media_library),
'post_content' => '',
'post_status' => 'inherit'
);

// Run the wp_insert_attachment function. This adds the file to the media library and generates the thumbnails. If you wanted to attch this image to a post, you could pass the post id as a third param and it'd magically happen.
$attach_id = wp_insert_attachment( $attachment, $file_name_and_location );
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_name_and_location );
wp_update_attachment_metadata($attach_id, $attach_data);

// Before we update the post meta, trash any previously uploaded image for this post.
// You might not want this behavior, depending on how you're using the uploaded images.
$existing_uploaded_image = (int) get_post_meta($post_id,'_lamvt_attached_image', true);
if(is_numeric($existing_uploaded_image)) {
wp_delete_attachment($existing_uploaded_image);
}

// Now, update the post meta to associate the new image with the post
update_post_meta($post_id,'_lamvt_attached_image',$attach_id);

// Set the feedback flag to false, since the upload was successful
$upload_feedback = false;

} else { // wp_handle_upload returned some kind of error. the return does contain error details, so you can use it here if you want.

$upload_feedback = 'There was a problem with your upload.';
update_post_meta($post_id,'_lamvt_attached_image',$attach_id);

}

} else { // wrong file type

$upload_feedback = 'Please upload only image files (jpg, gif or png).';
update_post_meta($post_id,'_lamvt_attached_image',$attach_id);

}

} else { // No file was passed

$upload_feedback = false;

}

// Update the post meta with any feedback
update_post_meta($post_id,'_lamvt_attached_image_upload_feedback',$upload_feedback);

break;

default:

} // End switch

return;

} // End if manual save flag

return;

}
add_action('save_post','lamvt_update_post',1,2);

 

Xác lập quyền, sở hữu và an ninh

Nếu bạn gặp sự cố trong khi tải ảnh lên, có thể nó liên quan tới quyền quản trị trong trang nội dung. Để giải quyết vấn đề này, trước tiên, bạn phải đảm bảo rằng thư mục wp-content / uploads của bạn tồn tại và thuộc sở hữu của apache: apache.  Nếu vậy, bạn sẽ có thể thiết lập quyền truy cập đến 744. Quyền sở hữu rất quan trọng – thậm chí đặt perms đến 777 đôi khi sẽ không giúp đỡ nếu thư mục không phải là sở hữu đúng.

Bạn cũng nên xem xét hạn chế các loại tệp được tải lên và thực hiện bằng tệp htaccess.  Điều này ngăn người tải lên các tệp không phải là hình ảnh và từ thực thi các tập lệnh được ngụy trang dưới dạng hình ảnh.
Việc xây dựng trường tải ảnh trực tiếp vào bài viết trong trang quản trị website là điều rất quan trọng. Nó góp phần làm tăng thêm tính tương tác của người dùng vào bài viết, như vậy độ tin tưởng website sẽ tăng cao. Bởi vậy, bạn cần tìm hiểu thật kỹ vấn đề này để xử lý thật tốt.

<Files ^(*.jpeg|*.jpg|*.png|*.gif)>
order deny,allow
deny from all
</Files>

Xem thêm: Cài đặt gửi tin nhắn Chat Facebook vào WordPress

About

Chào bạn, mình là Vũ Thành Lâm.
Tri Thức là Sức Mạnh, Tri thức không của riêng ai, hãy chia sẻ nó!

Recent posts