Invalid argument supplied for foreach() .. Wordpre

2019-07-17 08:17发布

Suddenly starting getting this error for the following code:

<?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; ?> 

Sometimes the taxonomy 'loan-club' is empty. Could that be the problem? If so, could someone point me towards the correct code?

标签: php wordpress
2条回答
姐就是有狂的资本
2楼-- · 2019-07-17 08:22

<?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.

查看更多
做自己的国王
3楼-- · 2019-07-17 08:33

Add if condition before 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
    } 
}
?>

Look at get_the_terms() function in the documentation: https://developer.wordpress.org/reference/functions/get_the_terms/

The function may also return WP_Error or false. If WP_Error or false is returned this will cause the error and the foreach loop breaks.

查看更多
登录 后发表回答