我对php很陌生。我在一些Wordpress页面上出现了这些错误。
警告: count():参数必须是在第38行的/www/tastingvictoria_289/public/wp-content/themes/astra-child/template-parts/content-single.php中实现可数的数组或对象
警告:为第40行的/www/tastingvictoria_289/public/wp-content/themes/astra-child/template-parts/content-single.php中的foreach()提供的无效参数
这是相关代码。
<?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 ' ';
}
}
?>有什么解释吗?
发布于 2022-07-19 03:36:27
作为错误消息,传递到count()函数的$term参数是而不是可数(在某些情况下,post id不是退出)。
若要解决此问题,请将代码更改为:
<?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 class="category"><span><a class="" href="' . $term_link . '">' . $term->name . '</a></span></p>';
if ($i != $total) echo ' ';
}
}
}
?>发布于 2022-07-19 04:01:19
将$terms转换为数组以获得count($terms)的有效结果。
发布于 2022-07-19 06:08:37
get_the_terms() 在成功时返回WP_Term对象的数组,如果没有条件或不存在post,则返回WP_Error失败。
可能是不存在的条件。尝试以下几个方面:
$terms = get_the_terms( $post->ID , 'category' );
if ( $terms && ! is_wp_error( $terms ) ) :
$total = count($terms);
$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 ' ';
}
}
endif;https://stackoverflow.com/questions/73030485
复制相似问题