Quantcast
Channel: プラグイン検証用-FTPup
Viewing all articles
Browse latest Browse all 88

メディアの日本語ファイル名対策

$
0
0

日本語名の画像ファイルアップロード時、ファイル名を英数字に変更する(ブロックエディタ対応)

https://nendeb.com/815

/*
 * 画像登録時、アップロードするファイル名を 変更する
 * post_parentより $post_id を取得して ファイル名を生成する
 *
 * @param string $filename     Sanitized filename.
 * @param string $filename_raw The filename prior to sanitization.
 * License: GPLv2 or later
 */
function nendebcom_rename_upload_file( $filename, $filename_raw ){
 
    global $old_filename;
 
    $old_filename = $filename_raw;
 
    $name = pathinfo( $filename, PATHINFO_BASENAME );
    // ファイル名を小文字に変換
    $name = strtolower( $name );
    //sitemap.xml自動生成時は何もしない
    if ( $name == 'sitemap' ) {
        return $filename;
    }
 
    // 拡張子を取得
    $ext = pathinfo( $filename, PATHINFO_EXTENSION );
    $ext = strtolower( $ext );
    if ( $ext ) {
        $ext = '.' . $ext;
    }
 
    // post_parent 取得 (旧エディタ)
    $post_id = isset( $_POST['post_id'] ) ? (int)$_POST['post_id'] : ''; 
 
    // post_parent 取得 (ブロックエディタ)
    if( !$post_id ){
        $post_id = isset( $_POST['post'] ) ? (int)$_POST['post'] : ''; 
    }
 
    // $post_idよりファイル名を生成する
    if( $post_id ){
 
        //商品番号
        $item_no = get_post_meta( $post_id, 'item_no', true );
 
        if( $item_no != '' ){
            $filename = 'item_' . $item_no . $ext;      // 商品番号ベースのファイル名
        }else{
            $filename = 'post_' . $post_id . $ext;      // post_idベースのファイル名
        }
 
    // メディアアップロードの場合
    }else{
        $filename = 'media' . $ext;     // media
    }
 
    return $filename;
}
add_filter( 'sanitize_file_name', 'nendebcom_rename_upload_file', 10, 2 );
 
 
/**
 * アップロードした ファイル名をタイトルにする
 * Fires after a single attachment is completely created or updated via the REST API.
 *
 * @since WordPress 5.0.0
 * @param WP_Post         $attachment Inserted or updated attachment object.
 * @param WP_REST_Request $request    Request object.
 * @param bool            $creating   True when creating an attachment, false when updating.
 * License: GPLv2 or later
 */
function nendebcom_rename_upload_title( $attachment, $request ){
 
    global $old_filename;
 
    if( $attachment->post_type == 'attachment' && $old_filename ){
        //アップロードしたファイル名から拡張子を外してタイトルにする
        $ext  = pathinfo( $old_filename, PATHINFO_EXTENSION );
        $file_title = str_replace( '.' . $ext, '', $old_filename );
 
        //タイトルを更新
        $update_attachment = array(
            'ID'         => $attachment->ID,
            'post_title' => $file_title
        );
 
        wp_update_post( $update_attachment );
    }
}
add_action( 'rest_after_insert_attachment', 'nendebcom_rename_upload_title', 10, 2 );

Viewing all articles
Browse latest Browse all 88

Trending Articles