PHP の「Notice: Undefined index」「Warning: Undefined array key」の直し方:WordPress の post_type を例に

広告WordPress・PHP を学べる本

Amazonのアソシエイトとして、WordPress functions.phpは適格販売により収入を得ています。

概要説明

WordPress のテーマやプラグインで出る「Notice: Undefined index: post_type」(PHP 8 では「Warning: Undefined array key "post_type"」)の原因と直し方。?? ・isset・get_query_var の書き方を、PHP 7.3 と 8.3 で確かめた結果つきで。

次のように、配列の中の値をそのまま読む書き方で出ます。

$post_type = $wp_query->query['post_type'];

一見問題なさそうですが、post_type という値がないとき(トップページや固定ページなど)のことを考えていません。ない値を読もうとすると、PHP がお知らせを出します。

PHP のバージョン 出る文
PHP 7 まで Notice: Undefined index: post_type
PHP 8 から Warning: Undefined array key “post_type”

PHP 8 では「お知らせ(Notice)」から「警告(Warning)」に上がっています。PHP を上げたら、ログに警告がたくさん出るようになった、というときによくある原因の 1 つです。

確かめた結果

post_type のない配列で、前の書き方と直した書き方を、PHP 7.3 と 8.3 で動かしました。

試したコード
$query = array( 'name' => 'sample' ); // post_type がない

$a = $query['post_type'];                                        // 前の書き方
$b = isset( $query['post_type'] ) ? $query['post_type'] : false; // isset
$c = $query['post_type'] ?? false;                               // ??
書き方 PHP 7.3 PHP 8.3
前の書き方 Notice: Undefined index: post_type Warning: Undefined array key “post_type”
isset・?? お知らせなし(false) お知らせなし(false)

直し方:値があるかを確かめてから読む

functions.php など
// 1. ?? (値がなければ右の値)。PHP 7.0 から使える、いちばん短い書き方
$post_type = $wp_query->query_vars['post_type'] ?? false;

// 2. isset で確かめてから使う
$post_type = isset( $wp_query->query_vars['post_type'] ) ? $wp_query->query_vars['post_type'] : false;

// 3. WordPress の関数で取る(メインのクエリの値。なければ空の文字)
$post_type = get_query_var( 'post_type' );
書き方 向いているとき
?? いちばん短い。ないときの値も決められる(PHP 7.0 から)
isset() で分ける あるときとないときで、処理を大きく分けたいとき
get_query_var() WordPress のメインのクエリの値を読むとき。ないときは空の文字が返る

Undefined index・Undefined array key は、どちらも「ない値を読もうとした」というお知らせです。?? か isset で、値があるかを確かめてから読めば出なくなります。

関連機能

  1. PHP 8 で空の文字と 0 の比べ方が変わり、カテゴリーのボタンが消えた:文字と数の比べ方の変更と、テーマの直し方

  2. サイトマップエラー error on line 2 at column 6: XML declaration allowed only at the start of the document の修正…

  3. WordPressで長い記事を書いていたら更新データが保存されなくなった時の対応 ( エックスサーバー )

サイドバー

よく使うカスタマイズ

最近の記事

Profile

PAGE TOP