Search code examples
phpwordpresswordpress-themingphp-7.3

Trying to update to PHP 7.4 but getting this error in an element, Warning: count(): Parameter must be an array or an object that implements Countable


Hey there I am new here heard a lot about this helpful community. I'm trying to update my custom build a theme to PHP 7.4 but during compatibility testing I found this error, any help would be appreciated.

I have 0 knowledge of PHP (currently)

Here is the code.

$type_terms = get_the_terms( $post->ID,"property-type" );
$type_count = count($type_terms);
if(!empty($type_terms)){
    echo '<small> - ';
    $loop_count = 1;
    foreach($type_terms as $typ_trm){
        echo $typ_trm->name;
        if($loop_count < $type_count && $type_count > 1){
            echo ', ';
        }
        $loop_count++;
    }
    echo '</small>';
}else{
    echo '&nbsp;';
}
?>
            </span>
        </h5>
    </div>

    <div class="property-meta clearfix">
        <?php

Thanks


Solution

  • from the WordPress documentation about get_the_terms :

    Return: Array of WP_Term objects on success, false, if there are no terms or the post, does not exist, WP_Error on failure.

    that means get_the_terms function will return 1 of these 3 options :

    1. false
    2. error
    3. array

    if the post has some "terms" then you will get no warnings, but it occurs when you try to count some results that are not a valid array (or any countable object). so you can check for it befor you try to count the fetched terms :

    if(is_array($type_terms))
       $type_count = count($type_terms);
    else 
       $type_count = [];
    

    or with ternary operation:

    $type_count = is_array($type_terms) ? count($type_terms); : [] ;