web-dev-qa-db-ja.com

ディレクトリから別のディレクトリにファイルを移動する

私はこの機能があります。

function attachment_selectbox_edit($form_fields, $post) {

$select_options = array(
    "no" => "No",
    "yes" => "Yes"
);

// get the current value of our custom field
$current_value = get_post_meta($post->ID, "_my_select", true);

// build the html for our select box
$mySelectBoxHtml = "<select name='attachments[{$post->ID}][my_select]' id='attachments[{$post->ID}][my_select]'>";
foreach($select_options as $value => $text){

    // if this value is the current_value we'll mark it selected
    $selected = ($current_value == $value) ? ' selected ' : '';

    // escape value for single quotes so they won't break the html
    $value = addcslashes( $value, "'");

    $mySelectBoxHtml .= "<option value='{$value}' {$selected}>{$text}</option>";
}
$mySelectBoxHtml .= "</select>";

// add our custom select box to the form_fields
$form_fields["my_select"]["label"] = __("Move the file?");
$form_fields["my_select"]["input"] = "html";
$form_fields["my_select"]["html"] = $mySelectBoxHtml;

return $form_fields;
}
add_filter("attachment_fields_to_edit", "attachment_selectbox_edit", null, 2);

$ current_value == 'yes'のときに、ファイルを "uploads"ディレクトリから "uploads/new-directory"に移動します。

手伝って頂けますか?

1
user1443216

特にattachment_fields_to_editが複数の場所で使用される可能性があるので、まだ(編集フォームが保存されているところで)これを処理するための正しいフィルタを見つけ出すことはできません。しかし、あなたはすでに知っていますか?とにかくこれはあなたに良いスタートを与えるでしょう...

add_filter('??attachment_fields_save_filter??','move_attachment_directory',10,2);

function move_attachment_directory($form_fields,$post) {

$attach_id = $post->ID;
if (!isset($_POST['attachments'][$attach_id]['my_select'])) {return;}
if ($_POST['attachments'][$attach_id]['my_select'] == 'no') {return;}

// set directories
$uploaddir = wp_upload_dir();
$newdirectory = 'new-directory'; // or whatever it is

// get attachment metadata
$attachdata = wp_get_attachment_metadata($attach_id);

// move original image
$filepath = trailingslashit($uploaddir).$attachdata['file'];
$newfilepath = trailingslashit($uploaddir).trailingslashit($newdirectory).$attachdata['file'];
rename($filepath,$newfilepath);
$attachdata['file'] = trailingslashit($newdirectory).$attachdata['file'];

// move each attachment size too
foreach ($attachdata['sizes'] as $size => $data) {
    $file = $data['file'];
    $filepath = trailingslashit($uploaddir).$data['file'];
    $newfilepath = trailingslashit($uploaddir).trailingslashit($newdirectory).$data['file'];
    rename($filepath,$newfilepath);
    $data['file'] = trailingslashit($newdirectory).$data['file'];
    $attachdata['sizes'][$size] = $data;
}

// update attachment metadata
wp_update_attachment_metadata($attach_id,$attachdata);

}

注:月/年でソートされたメディアがある場合、これがそのまま機能するとは思いません。

いずれにせよ、これはテストされていないコードであり、パスのバグなどがあるかもしれません。そのため、テスト環境で何らかの作業が必要になるかもしれませんが、できます。

2
majick