Thêm tên bài viết và ký tự ngẩu nhiên vào file hình khi upload trong bài viết WordPress

Wordpress Giza Data Tháng hai 16, 2023

Để áp dụng vào WordPress, bạn có thể sử dụng một plugin hoặc thêm mã PHP vào functions.php của theme.

Cách 1: Sử dụng plugin

Sử dụng plugin Có rất nhiều plugin cho phép bạn xử lý tên file trước khi upload, nhưng ở đây mình giới thiệu cho bạn plugin “Rename Media Files” do thương hiệu plugin hàng đầu của WordPress là Freemius phát triển. Đây là một plugin miễn phí và có thể tìm thấy trên trang WordPress.org.

Sau khi cài đặt và kích hoạt plugin, bạn có thể truy cập vào trang cấu hình của plugin để thiết lập tên file mới. Các tùy chọn cấu hình sẽ cho phép bạn xóa các ký tự không mong muốn, thay thế khoảng trắng bằng dấu gạch ngang, thêm tiền tố hoặc hậu tố vào tên file. Sau khi lưu cấu hình, plugin sẽ tự động xử lý tên file trước khi upload.

Cách 2: Theme code vào file funtion của theme

Thêm mã PHP vào functions.php của theme Nếu bạn muốn tự tay xử lý tên file bằng mã PHP, bạn có thể thêm đoạn mã sau vào functions.php của theme:

PHP
add_action( 'add_attachment', 'rename_uploaded_file' );
add_filter('wp_handle_upload_prefilter', 'custom_upload_filter');

function rename_uploaded_file( $attachment_id ) {
    $post_id = wp_get_post_parent_id( $attachment_id );
    if ( $post_id ) {
        $post_title = get_the_title( $post_id );
        $file = get_attached_file( $attachment_id );
        $path = pathinfo( $file );
        $new_filename = sanitize_file_name( $post_title ) . '_' . $path['filename'] . '_' . wp_generate_password( 4, false ) . '.' . $path['extension'];
        $new_file = $path['dirname'] . '/' . $new_filename;
        rename( $file, $new_file );
        update_attached_file( $attachment_id, $new_file );
    }
}

function custom_upload_filter($file) {
    $post_id = $_REQUEST['post_id'];
    $post_title = get_the_title($post_id);
    $file['name'] = wp_unique_filename($file['upload_path'], sanitize_file_name($post_title) . '_' . $file['name']);
    $file['name'] = pathinfo($file['name'], PATHINFO_FILENAME) . '_' . wp_generate_password( 4, false ) . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
    return $file;
}
Quảng Cáo