[WP] PHP7.2 にした時に post-template.php で発生する Warring への対処

Program,WordpressPHP,WP-カスタマイズ

PHP7.2にして、Wordpressを動かして見ると、

count(): Parameter must be an array or an object that implements Countable in …(ファイルパス)/wp-includes/post-template.php on line 284

なワーニングメッセージが。

調べてみるとPHP7.2 になって count関数 が変わった模様。
PHP 公式マニュアル

バージョン 説明
7.2.0 count() will now yield a warning on invalid countable types passed to the array_or_countable parameter.

引数が配列かカウントできるオブジェクトじゃないとワーニングを出しますよー。
ってことになったらしい。

で、件の post-template.php では

if ( $page > count( $pages ) ) // if the requested page doesn't exist
	$page = count( $pages ); // give them the highest numbered page that DOES exist

と $pages がどんなオブジェクトがわからないまま、count関数の引数に使われているのでワーニングが出た模様。

$pages が空(NULL)の場合にワーニングが出るので、count関数を使う前に$pagesが空かどうかのチェックを入れればOK。
空の場合は0を入れてあげます。

if ( ! empty( $pages )) {
    if ( $page > count( $pages ) ) // if the requested page doesn't exist
    	$page = count( $pages ); // give them the highest numbered page that DOES exist
} else {
    $page = 0;
}

コンピュータプログラムの世界では 空(NULL) = 0 かどうかか環境依存だったりするので、ややこしいですね。



ひとまず該当箇所を修正して、ファイルを上書きすればワーニングは出なくなります。