説明
wp_get_image_editor() は、画像の加工(リサイズ・切り抜き・回転など)用のエディターオブジェクトを返す関数です。
基本構文
wp_get_image_editor( string $path, array $args = array() ): WP_Image_Editor|WP_Error
引数
$path:画像のファイルパス$args:オプション
戻り値
WP_Image_Editor。失敗時は WP_Error。
使い方(サンプル)
$editor = wp_get_image_editor( $path );
if ( ! is_wp_error( $editor ) ) {
$editor->resize( 300, 300, true );
$editor->save( $new_path );
}
注意点
- サーバーにGDまたはImageMagickが必要です。
- 失敗時の
WP_Errorを必ず確認します。
実務での使いどころ
- 画像を、プログラムでリサイズ、切り抜き、回転するとき。
- アップロードされた画像から、独自のサイズの画像を作るとき。
よくあるミスと対処
- 戻り値が
WP_Errorのときを、考えていない。画像を扱えない環境や、不正なファイルで、エラーが返る。 - 加工したあと、
save()を呼んでいない。加工結果が、保存されない。 - URLを渡している。渡すのは、サーバー上のファイルのパス。
NG例
$editor = wp_get_image_editor( $path );
$editor->resize( 300, 300, true ); // エラーの確認も、保存もない
OK例
$editor = wp_get_image_editor( $path );
if ( ! is_wp_error( $editor ) ) {
$editor->resize( 300, 300, true );
$saved = $editor->save();
}
使い分け早見表
| やりたいこと | 使うもの |
|---|---|
| 画像を加工する | wp_get_image_editor() |
| 画像の種類(MIME)を、中身から判定 | wp_get_image_mime() |
| ファイル名(拡張子)から判定 | wp_check_filetype() |
関連項目
get_intermediate_image_sizes()、wp_insert_attachment()、wp_get_image_mime()
公式リファレンス:wp_get_image_editor() | Function | WordPress Developer Resources

コメント