WordPressでphp7.2にした時にWarning: count()が出た場合の治し方(コピペ可)

WordPressというCMSでは、phpというWebプログラミング言語を使って構成されているのですが、そのphpにも色々なバージョンがあります。

で、そのバージョンが7.2っていうのが、一応Wordpressの推奨バージョンということで早速バージョンアップをしたのですが、その際にWarning: count(): Parameter must be an array or an object that implements Countable in …(ファイルパス)/wp-includes/post-template.php on line 284という表示が出てしまってびっくりしたのと、その治し方をご紹介します。

ファイルを開こう

上記パスにはwp-includesディレクトリの中にあるpost-template.phpの284行目と書かれていますので、そのファイルを見てみましょう。

そこの284行目付近にはこのように書かれています。

 

// If post password required and it doesn't match the cookie.
	if ( post_password_required( $post ) )
		return get_the_password_form( $post );

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

それをこのように変えます。

// If post password required and it doesn't match the cookie.
	if ( post_password_required( $post ) )
		return get_the_password_form( $post );
    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;
	}

これで表示は消えると思います。

症状が出る理由

PHP7.2で count()関数の仕様が変更に

エラーメッセージ「Parameter must be an array or an object that implements Countable」を訳すと、「パラメータは配列か、カウントできる機能が実装されたオブジェクトでなければならない」という意味になります。

phpの公式サイトによると、このように書かれています。

In PHP 7.2.0
count(NULL) returns a warning:
Warning: count(): Parameter must be an array or an object that implements Countable

In previous versions:
count(NULL) returned 0 without any warnings.

前のバージョンではcount(NULL)では警告が出ずに0を返しますが一方、7.2バージョンでは警告を出しますよーとのことです。

post-template.phpで何があったの?

count( $pages ) の $pages が宣言だけされて、初期化の前に、285行目でcount() に代入されたことにより、Warningが出たんだと思います。

なので!empty→エンプティでない場合という条件を加えてあげることで、警告を回避します。

まあ、この表示が出たらコピペしてファイルをアップロードしてあげてくださいね。

About the author

Kazuhito Naozuka Representative Director / Web Director / Programmer

Based in Saga City, supporting web strategy for small and medium-sized businesses and sole proprietors. Handling everything from website creation to SaaS development, SEO optimization, and ad management across the digital domain. Our mission is to accelerate the growth of regional businesses through "technical expertise × strategic proposals." We have been involved in numerous projects to date.