简体   繁体   中英

PHP Error - Warning: count(): Parameter must be an array or an object that implements Countable

The full error is: "Warning: count(): Parameter must be an array or an object that implements Countable in /app/public/wp-content/themes/site/inc/lists_posts.php on line 54"

It's saying line 54 which is where the first if statement starts.. Any idea how I can fix this?

<?php foreach($projects as $key => $project){
$display = true;
$terms = get_the_terms($project->ID,"diadem_project_category");

if(count($terms) == 1){
    // function located in function.php
    $display = check_project_display($terms[0]->term_id);
}

if($display){
    
    $permalink = get_permalink($project->ID);
    $project_caption = get_field('project_caption',$project->ID);
    $type = get_field('type',$project->ID);
    $subscript_number = get_field('subscript_number',$project->ID);
    $download_pdf = get_field('download_pdf',$project->ID);
    $thumbnail = get_the_post_thumbnail_url($project->ID);
    $image_url = wp_get_attachment_image_src( get_post_thumbnail_id($project->ID), 'medium');
    $categories = wp_get_post_terms($project->ID, $category_name, array("fields" => "all"));
    
    $target ="";
    
    $slug = "";
    if($categories){ 
        foreach($categories as $cat){ 
            $slug .= $cat->slug." "; 
            
            if($category_name == "diadem_insight_category"){
                $project_caption = $cat->name;
            }
            
        } 
    }
    
    $project->post_title = str_replace("'","’",$project->post_title);

    
?>

Sometimes while getting data, some errors occurs which return false instead of result set. So before checking data length, we should compare output type too.

if($terms !== false && count($terms) == 1){
    // function located in function.php
    $display = check_project_display($terms[0]->term_id);
}

And also I think you might get n terms not only one. In that case

if($terms !== false && count($terms) >= 1){
    // function located in function.php
    $display = check_project_display($terms[0]->term_id);
}

首先使用var_dump($terms)echo gettype($terms)检查变量$terms的数据类型。它必须是数组或对象,然后才不会发生警告。您使用的count()方法期望参数数据类型应该是arrayobject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM