foreach error on false boolean from get_terms

I’m grabbing an array of page ids that were created in another function which I use regularly- that’s all good. The issue I have is in the below function. Some pages have not been assigned an “interest” from the options in the interest taxonomy. Therefore the $terms array has some false booleans from the pages without terms. When the foreach runs into these false booleans a php error appears on the screen, although the loop continues running and works as expected in all other ways. How can I stop this error from showing up? I need some sort of error catcher for the false booleans but not sure how to go about it. Any advice is much appreciated!

foreach ($campids as $campid){
            $terms = get_the_terms($campid, 'interests');

            foreach($terms as $term){
                $camp_int = $term->name;

                if ($camp_int == $interest){ // include only camps with the correct location
                    $camps[$i]['id']=$campid;
                    $camps[$i]['interest']=$camp_int;
                }
            }
            $i++;
        }

Related posts

Leave a Reply

1 comment

  1. What you need is pretty much straight out of the Codex:

    $terms = get_the_terms( $post->ID, 'on-draught' );
    
    if ( $terms && ! is_wp_error( $terms ) ) : 
    
        $draught_links = array();
    
        foreach ( $terms as $term ) {
            $draught_links[] = $term->name;
        }
    

    get_the_terms() can return a term object, false, or a WP_Error object. You are checking for neither the false nor the error object. That is what this conditional does:

    if ( $terms && ! is_wp_error( $terms ) ) 
    

    Use it instead of if(is_array($terms)){