簡體   English   中英

將附件文件重命名為在Wordpress中添加到的帖子標題

[英]Renaming attachment files to the post title it's being added to in Wordpress

就像標題說的那樣,我試圖將媒體庫上傳的文件重命名為文件要添加到的初始帖子的標題。

我找到了以下函數,並對其進行了修改,以將文件名更改為文件的作者子彈

// file renamer (used for EDL images)
function file_renamer( $filename ) {
  $info = pathinfo( $filename );
  $ext  = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
  $name = basename( $filename, $ext );
  global $current_user;
  get_currentuserinfo();

  return   $current_user->user_login . $ext;
}

但是,這對於客戶來說還不夠好。 我尚未在線找到任何解決方案。 任何幫助將不勝感激!

編輯-只想補充一點,我也為此使用了高級自定義字段。 這是此過程的其余代碼,它將特定的自定義字段圖像定向到某個目錄,

// EDL uploaded images will go to the /edl directory in uploads for these fields.
add_filter('acf/upload_prefilter/name=edl_dealer_logo', 'field_name_upload_prefilter');
add_filter('acf/upload_prefilter/name=edl_image', 'field_name_upload_prefilter');
add_filter('acf/upload_prefilter/name=edl_gallery_image', 'field_name_upload_prefilter');

function field_name_upload_prefilter($file) {
// in this filter we add a WP filter that alters the upload path
add_filter( 'sanitize_file_name', 'file_renamer', 10 );
add_filter('upload_dir', 'field_name_upload_dir');
return $file;
}
// second filter
  function field_name_upload_dir($uploads) {

  $mydir = '/edl';
  // here is where we later the path
  $uploads['path'] = $uploads['basedir'].$mydir;
  $uploads['url'] = $uploads['baseurl'].$mydir;

  $uploads['subdir'] = '/edl';
  return $uploads;
}

我想您也許可以看一下$_POST["post_ID"] ,使用WP的get_post() ,然后如果找到了一個帖子,請調用get $post->post_title作為文件名。

還是ACF是通過Ajax異步上傳的? 無論如何,我認為應該在上傳時發送帖子ID,但是您可能必須查看瀏覽器的開發人員工具才能知道字段名稱是什么。

以下在我的安裝中有效。 請注意,此操作將在所有文件上傳中運行,因此您可能需要添加一些預防措施。

function file_renamer( $filename ) {
    $info = pathinfo( $filename );
    $ext  = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
    $name = basename( $filename, $ext );
    if( $post_id = array_key_exists("post_id", $_POST) ? $_POST["post_id"] : null) {
        if($post = get_post($post_id)) {
            return $post->post_title . $ext;
        }
    }
    get_currentuserinfo();

    return   $current_user->user_login . $ext;
  }
add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM