I have a WooCommerce WordPress Theme installed.

I'm getting an error that public users can see, So I need to fix it ASAP.

The error is shown on all products pages, Here is the error:

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

Here is the related code:

global $product, $post, $smof_data;
$cat_count = sizeof(get_the_terms($post->ID, 'product_cat'));
$tag_count = sizeof(get_the_terms($post->ID, 'product_tag'));

The error is from the last line of the above code.

I could do something like checking if that get_the_terms($post->ID, 'product_tag') is an array first, Else assign it to empty '' or 0.

But not sure if this would affect other code.

How to solve this issue without affecting any other related code?


Let's take a look at get_the_terms Codex page. We can find there that this function may return:

(array|false|WP_Error) Array of WP_Term objects on success, false if there are no terms or the post does not exist, WP_Error on failure.

So your code will work correct only in one case - when the function returns an array of terms.

But it may also return a WP_Error if any error occurs or false if there are no terms for that post in given taxonomy.

So yes - you should always include proper error checking in your code. It may look like this:

global $product, $post, $smof_data;
$cats = get_the_terms($post->ID, 'product_cat');
$cat_count = ( !empty( $cats ) && ! is_wp_error( $cats ) ) ? count($cats) : 0;
$tags = get_the_terms($post->ID, 'product_tag');
$tag_count = ( !empty( $tags ) && ! is_wp_error( $tags ) ) ? count($tags) : 0;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.