在使用wordpress建站过程中使用php7.2版本测试主题时发现,当wp版本切换7.2会出现以下错误
Warning: count(): Parameter must be an array or an object that implements Countable in /wp-includes/media.php on line 1206
报错原因
首先来看一下 count() 的方法原型。其中 $array_or_countable 参数,需要是数组或者 Countable 对象(Countable 接口能让对象可以被用于count函数的能力)。在 PHP 7.2 中对于 count() 有一个新增的变更,具体可参考官网文档。
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
也就是说在 7.2 版本中当无效的类型传递给 $array_or_countable 参数时,count() 会产生警告,所以我们可以知道,上面提到的报错应该是传了无效的类型给 count() 才导致发出的警告
再看一下上面提到的报错位置 /wp-includes/media.php on line 1206 ,接下来我们就看一下 /wp-includes/media.php 在 1206 行有啥东西吧。
/**
* Filters an image's 'srcset' sources.
*
* @since 4.4.0
*
* @param array $sources {
* One or more arrays of source data to include in the 'srcset'.
*
* @type array $width {
* @type string $url The URL of an image source.
* @type string $descriptor The descriptor type used in the image candidate string,
* either 'w' or 'x'.
* @type int $value The source width if paired with a 'w' descriptor, or a
* pixel density value if paired with an 'x' descriptor.
* }
* }
* @param array $size_array Array of width and height values in pixels (in that order).
* @param string $image_src The 'src' of the image.
* @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
* @param int $attachment_id Image attachment ID or 0.
*/
$sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );
// Only return a 'srcset' value if there is more than one source.
if ( ! $src_matched || count( $sources ) < 2 ) {
return false;
}
看代码发现 1206 行在一个名叫 wp_calculate_image_srcset 的方法中,而且 count 调的 $sources 也是一个数组。那么只能说明在不知道哪里调用 wp_calculate_image_srcset 方法的时候,传过来的 $sources 是一个非数组,所以出现了这个问题,那么应该在调用 count 之前确保 $sources 是一个数组就成了,所以我们这里加一个判断 ! is_array( $sources ) 就可以了,所以修改之后的代码如下
/** * Filters an image's 'srcset' sources. * * @since 4.4.0 * * @param array $sources { * One or more arrays of source data to include in the 'srcset'. * * @type array $width { * @type string $url The URL of an image source. * @type string $descriptor The descriptor type used in the image candidate string, * either 'w' or 'x'. * @type int $value The source width if paired with a 'w' descriptor, or a * pixel density value if paired with an 'x' descriptor. * } * } * @param array $size_array Array of width and height values in pixels (in that order). * @param string $image_src The 'src' of the image. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'. * @param int $attachment_id Image attachment ID or 0. */ $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id ); // Only return a 'srcset' value if there is more than one source. if ( ! $src_matched || ! is_array( $sources ) || count( $sources ) < 2 ) { return false; }
评论前必须登录!
注册