I am new to php. I have these errors appearing on some WordPress pages.
Warning: count(): Parameter must be an array or an object that implements Countable in /www/tastingvictoria_289/public/wp-content/themes/astra-child/template-parts/content-single.php on line 38
Warning: Invalid argument supplied for foreach() in /www/tastingvictoria_289/public/wp-content/themes/astra-child/template-parts/content-single.php on line 40
This is the related code.
<?php $terms = get_the_terms( $post->ID , 'category' );
$total = count($terms); // 38
$i=0;
foreach ( $terms as $term ) {
if($term->slug != "featured-post"){
$i++;
$term_link = get_term_link( $term, 'category' );
if( is_wp_error( $term_link ) )
continue;
echo '<p class="category"><span><a class="" href="' . $term_link . '">' . $term->name . '</a></span></p>';
if ($i != $total) echo ' ';
}
}
?>
Any explanation?
4
Answers
As the error message, the $term parameter that you pass into count() function is not countable (in some case – eg, the post id is not exit).
To fix this, please change your code into:
Convert the
$terms
to an array for getting valid result ofcount($terms)
.get_the_terms()
returns Array of WP_Term objects on success, false if there are no terms or the post does not exist, WP_Error on failure.May be the terms not exists. Try following:
Mainly the get_the_terms() function behind code like this
In this case, you can see if there is no post then it’ll return false, and if the function returns false then your code will be like this:
Note: the count() function accept an array or object and the foreach() function accept iterable_expression as well. That is why you’re getting the warnings.
So, in that case, you can check the return output of the get_the_terms() function like this:
Thank you