is_wp_error() の使い方|説明・引数・注意点

説明

is_wp_error() は、変数が WP_Error オブジェクトかを判定する関数です。WordPressの関数の失敗を調べるときの基本です。

基本構文

is_wp_error( mixed $thing ): bool

引数

  • $thing:調べる値

戻り値

WP_Error なら true。

使い方(サンプル)

$res = wp_remote_get( $url );
if ( is_wp_error( $res ) ) {
	error_log( $res->get_error_message() );
}

注意点

  • エラー内容は get_error_message()、get_error_code() で取得できます。
  • WP_Error を返しうる関数は、使う前に必ず判定します。

実務での使いどころ

  • wp_remote_get() や wp_insert_post() など、WP_Error を返すことがある関数の、結果を確認するとき。
  • エラーのときの処理を、分けるとき。

よくあるミスと対処

  • 結果を、そのまま if ( $result ) で判定している。WP_Error のオブジェクトは、真と判定される。
  • エラーのメッセージを、確認していない($error->get_error_message())。
  • 画面に、エラーの内容を、エスケープせずに出力している。

NG例

$response = wp_remote_get( $url );
if ( $response ) { // WP_Error も、真になる
	$body = wp_remote_retrieve_body( $response );
}

OK例

$response = wp_remote_get( $url );
if ( is_wp_error( $response ) ) {
	error_log( $response->get_error_message() );
	return;
}

使い分け早見表

確認したいこと 使うもの
WP_Error か判定 is_wp_error()
メッセージを取得 $error->get_error_message()
エラーコードを取得 $error->get_error_code()

関連項目

wp_remote_get()、wp_die()

公式リファレンス:is_wp_error() | Function | WordPress Developer Resources

コメント

タイトルとURLをコピーしました