wp_get_image_editor()


関数wp_get_image_editor()は、WordPressで画像の編集を行うために使用されます。この関数は画像サイズの変更やトリミング、画像フォーマットの変更など、さまざまな操作を可能にします。

シンタックス

wp_get_image_editor( string $path );
  • $path (string) — 編集する画像のパス。絶対パスを指定します。

例 1. 画像サイズを変更する

画像の幅を500ピクセルにリサイズする例です。

<?php
$editor = wp_get_image_editor( get_attached_file( $attachment_id ) );
if ( ! is_wp_error( $editor ) ) {
    $editor->resize( 500, null );
    $editor->save( get_attached_file( $attachment_id ) );
}
?>

例 2. 画像をトリミングする

画像を100×100ピクセルにトリミングします。

<?php
$editor = wp_get_image_editor( get_attached_file( $attachment_id ) );
if ( ! is_wp_error( $editor ) ) {
    $editor->crop( 0, 0, 100, 100 );
    $editor->save( get_attached_file( $attachment_id ) );
}
?>

例 3. サムネイルを作成する

サムネイル用に特定のサイズを持つ画像を作成します。

<?php
$editor = wp_get_image_editor( get_attached_file( $attachment_id ) );
if ( ! is_wp_error( $editor ) ) {
    $editor->resize( 150, 150, true );
    $editor->save( wp_get_upload_dir()['path'] . '/thumbnail.jpg' );
}
?>

例 4. 画像フォーマットを変更する

画像をPNG形式に変換します。

<?php
$editor = wp_get_image_editor( get_attached_file( $attachment_id ) );
if ( ! is_wp_error( $editor ) ) {
    $editor->save( wp_get_upload_dir()['path'] . '/image.png', 'image/png' );
}
?>

例 5. エラー処理の追加

画像編集プロセスでエラーが発生した場合の例です。

<?php
$editor = wp_get_image_editor( get_attached_file( $attachment_id ) );
if ( is_wp_error( $editor ) ) {
    echo 'エラー: ' . $editor->get_error_message();
} else {
    $editor->resize( 300, 300, true );
    $editor->save( get_attached_file( $attachment_id ) );
}
?>

注意事項

  • 編集対象の画像はサーバー上に存在している必要があります。
  • 関数がエラーを返した場合はis_wp_error()を使用してエラーメッセージを確認してください。
  • 画像を編集した後は、必ずsave()メソッドを使用して変更を保存してください。

関連機能: