ここから本文です
WordPressのファイルのアップロード先をポストタイプのディレクトリにする
WordPressのアップローダを使うと、年月日のディレクトリに保存するか、uploads直下に保存するかという2択になります。これをちょっといじって、ポストタイプ(+id)にしてみます。
functions.phpに以下を記述します。このhookでは、なにかの理由でPOST_TYPEが見つからない時には、uplaods/imagesに保存をします。
add_filter('upload_dir', 'my_upload_dir');
function my_upload_dir($upload)
{
$id = intval($_REQUEST['post_id']);
$dir = get_post_type($id) ?: 'images';
$upload['subdir'] = "/".$dir."/".$id;
$upload['path'] .= $upload['subdir'];
$upload['url'] .= $upload['subdir'];
return $upload;
}
管理画面「設定」「メディア」で「アップロードしたファイルを年月ベースのフォルダに整理」をオフにしてください。これで、保存先をpost_typeディレクトリ+idにできます。
くわえて、以下のような感じで、自前でアップローダを作っている場合は、javascriptでも配慮をします。
//=== uploadfile_admin_scripts ===
function uploadfile_admin_scripts()
{
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script('my-upload', get_stylesheet_directory_uri().'/js/jquery.inc.fileupload.js?post_id='.intval($_REQUEST['post']), array('jquery','media-upload','thickbox'));
wp_enqueue_script('my-upload');
}
function uploadfile_admin_styles()
{
wp_enqueue_style('thickbox');
}
add_action('admin_print_scripts', 'uploadfile_admin_scripts');
add_action('admin_print_styles', 'uploadfile_admin_styles');
ファイル名は適宜変えてもらったらいいですが、jquery.inc.fileupload.jsというような場合、以下のような感じになります。ポップアップを呼び出す時にidを渡してあげないと、post_typeを取得できないのですね。
jQuery(document).ready(function() {
// file uploads by custom field
var formfield;
// thx http://www.ipentec.com/document/document.aspx?page=javascript-get-parameter
function GetQueryString()
{
if (1 < document.location.search.length)
{
// 最初の1文字 (?記号) を除いた文字列を取得する
var query = document.location.search.substring(1);
// クエリの区切り記号 (&) で文字列を配列に分割する
var parameters = query.split('&');
var result = new Object();
for (var i = 0; i < parameters.length; i++)
{
// パラメータ名とパラメータ値に分割する
var element = parameters[i].split('=');
var paramName = decodeURIComponent(element[0]);
var paramValue = decodeURIComponent(element[1]);
// パラメータ名をキーとして連想配列に追加する
result[paramName] = decodeURIComponent(paramValue);
}
return result;
}
return null;
}
param = GetQueryString();
jQuery('.upload_image_button').click(function() {
jQuery('html').addClass('Image');
formfield = jQuery(this).prev().attr('id');
tb_show('', 'media-upload.php?post_id='+param["post"]+'&type=image&TB_iframe=true');
return false;
});
jQuery('.upload_file_button').click(function() {
jQuery('html').addClass('Image');
formfield = jQuery(this).prev().attr('id');
tb_show('', 'media-upload.php?post_id='+param["post"]+'&type=image&TB_iframe=true');
return false;
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html){
if (formfield) {
fileurl = jQuery('img',html).attr('src');
if(! fileurl){
fileurl = jQuery(html).attr('href');
}
jQuery('#'+formfield).val(fileurl);
tb_remove();
jQuery('html').removeClass('Image');
} else {
window.original_send_to_editor(html);
}
};
});

