問題描述

我想在上傳期間重命名文件,並將其名稱設置為文件所附加的帖子,再加上一些隨機字符 (一個簡單的增量計數器將會正常),使文件名不同。

換句話説,如果我正在上傳/附加圖片到頁面插件是”test-page-slug” 的帖子,我想要將圖像重命名為 test-page-slug-[C].[extension]

  • test-page-slug-1.JPG

  • test-page-slug-2.JPG

  • 等等,原來的文件名是不重要的。

有這個插件,Custom Upload Dir

With this plugin you can construct paths from additional variables like: post title, ID, category, post author, post date and much more.

怎樣才能做到文件名呢?

最佳解決方案

你想掛鈎到 wp_handle_upload_prefilter 過濾器 (我找不到任何文檔,但是看起來很簡單) 。我在本地嘗試過,似乎對我有用:

function wpsx_5505_modify_uploaded_file_names($arr) {

    // Get the parent post ID, if there is one
    if( isset($_REQUEST['post_id']) ) {
        $post_id = $_REQUEST['post_id'];
    } else {
        $post_id = false;
    }

    // Only do this if we got the post ID--otherwise they're probably in
    //  the media section rather than uploading an image from a post.
    if($post_id && is_numeric($post_id)) {

        // Get the post slug
        $post_obj = get_post($post_id);
        $post_slug = $post_obj->post_name;

        // If we found a slug
        if($post_slug) {

            $random_number = rand(10000,99999);
            $arr['name'] = $post_slug . '-' . $random_number . '.jpg';

        }

    }

    return $arr;

}
add_filter('wp_handle_upload_prefilter', 'wpsx_5505_modify_uploaded_file_names', 1, 1);

在我的測試中,看起來好像帖子只有一個 s lug if if if 。。。。。。。。。。。。。。。。。。。。。。。。。。。。你也想考慮檢查文件類型,我沒有在這裏做 – 我只是假設它是一個 jpg 。

編輯

根據評論的要求,此附加功能會更改上傳圖像的某些元屬性。似乎沒有讓您設置 ALT 文本,由於某些原因,您設置為”caption” 的值實際上被分配為描述。你必須和猴子一起玩。我在功能 wp_read_image_metadata() 中找到了這個過濾器,它位於 wp-admin /includes /image.php 中。這是媒體上傳,wp_generate_attachment_metadata 功能依賴於從圖像中提取元數據。如果你想要更多的洞察力,你可以看看那裏。

function wpsx_5505_modify_uploaded_file_meta($meta, $file, $sourceImageType) {

    // Get the parent post ID, if there is one
    if( isset($_REQUEST['post_id']) ) {
        $post_id = $_REQUEST['post_id'];
    } else {
        $post_id = false;
    }

    // Only do this if we got the post ID--otherwise they're probably in
    //  the media section rather than uploading an image from a post.
    if($post_id && is_numeric($post_id)) {

        // Get the post title
        $post_title = get_the_title($post_id);

        // If we found a title
        if($post_title) {

            $meta['title'] = $post_title;
            $meta['caption'] = $post_title;

        }

    }

    return $meta;

}
add_filter('wp_read_image_metadata', 'wpsx_5505_modify_uploaded_file_meta', 1, 3);

編輯 04/04/2012 從 REQUEST obj 中提取帖子 ID,而不是連續檢查 GET 和 POST 。根據意見中的建議。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。