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 ><span><a href="' . $term_link . '">' . $term->name . '</a></span></p>';
if ($i != $total) echo ' ';
}
}
?>
Any explanation?
CodePudding user response:
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:
<?php $terms = get_the_terms( $post->ID , 'category' );
if(is_array($terms)){
$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 ><span><a href="' . $term_link . '">' . $term->name . '</a></span></p>';
if ($i != $total) echo ' ';
}
}
}
?>
CodePudding user response:
Convert the $terms
to an array for getting valid result of count($terms)
.