固定 PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable 

出現在許多地方的 PHP 錯誤 WordPress Plugins 長時間未更新或與較新版本的 PHP 不兼容。 PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable.

在我們的場景中,PHP 錯誤發生在一個模塊中 Cross Sell Product Display 為 WooCommerce.

FastCGI sent in stderr: "PHP message: PHP Warning:  sizeof(): Parameter must be an array or an object that implements Countable in /web/path/public_html/wp-content/plugins/cross-sell-product-display-for-woocommerce/templates.php on line 18

為什麼會發生錯誤 PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable ?

產生這個 PHP 錯誤的問題是函數 sizeof() 在 PHP 7.2 或更高版本中,如果給定的參數不是一個,則會產生此錯誤 array 或實現接口的對象 Countable.

所以這個錯誤經常出現在PHP版本更新之後。

如何解決 PHP 產生的錯誤 sizeof()?

最簡單的方法是替換函數調用 sizeof() 通過函數調用 count().

對於那些使用舊版本模塊的人 Cross Sell Product Display,解決方法很簡單。 18 英寸系列的功能將被替換 templates.php.

function cdxfreewoocross_get_cross_sell_products($product_id=false){
	
	if($product_id ===false ){
		
		if(!is_product()){return false;}
		
		$product_id = (int)get_the_ID();
		if($product_id=='0'){return false;}
		
	}
	
	$crosssells = get_post_meta( $product_id, '_crosssell_ids',true);
	if ( sizeof($crosssells ) == 0  || $crosssells =='') { return false; }
	
	return $crosssells;
	
}

上面的代碼在其中 sizeof() 將被替換為:

function cdxfreewoocross_get_cross_sell_products($product_id=false){
	
	if($product_id ===false ){
		
		if(!is_product()){return false;}
		
		$product_id = (int)get_the_ID();
		if($product_id=='0'){return false;}
		
	}
	
	$crosssells = get_post_meta( $product_id, '_crosssell_ids',true);
	if ( !is_array( $crosssells ) || count( $crosssells ) == 0  || $crosssells =='') { return false; }
	
	return $crosssells;
	
}

此修改首先檢查是否 $crosssellsarray 使用函數 is_array() 否則返回 false.

的情況下 $crosssellsarray, 函數被使用 count() 確定元素的數量 array. 如果元素個數為零或 $crosssells 是一個空字符串,返回 false。

如果對本教程有任何澄清或補充,請發表評論。

對技術充滿熱情,我很高興寫 StealthSettings.com 自 2006 年起。我在作業系統方面擁有豐富的經驗: macOS, Windows 對 Linux,而且還包括程式語言和部落格平台(WordPress)和線上商店(WooCommerce、Magento、PrestaShop)。

如何 » WordPress » 固定 PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable 
發表評論