突然开始为以下代码收到此错误:
<?php foreach (get_the_terms(get_the_ID(), 'loan-club') as $cat) : ?>
<img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" title="ON LOAN AT: <?php echo $cat->name; ?>" />
<?php endforeach; ?>
有时候,分类学&#39; loan-club&#39;是空的。这可能是问题吗?如果是这样,有人能指出我正确的代码吗?
答案 0 :(得分:3)
在if
之前添加foreach
条件:
<?php
$loan_club = get_the_terms(get_the_ID(), 'loan-club');
if(is_array($loan_club)) {
foreach ($loan_club as $cat) {
?>
<img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" title="ON LOAN AT: <?php echo $cat->name; ?>" />
<?php
}
}
?>
请查看文档中的get_the_terms()函数:https://developer.wordpress.org/reference/functions/get_the_terms/
该函数也可能返回WP_Error或false。如果返回WP_Error或false,则会导致错误并且foreach循环中断。
答案 1 :(得分:1)
<?php foreach ((array)get_the_terms(get_the_ID(), 'loan-club') as $cat) : ?>
<img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" title="ON LOAN AT: <?php echo $cat->name; ?>" />
<?php endforeach; ?>
Note: to all the people complaining about typecast, please note that the OP asked cleanest way to skip a foreach if array is empty (emphasis is mine). A value of true, false, numbers or strings is not considered empty.