WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've got a custom post type which displays portfolio items. I display the portfolio category on the page using this code:

<?php 
$myterms = get_the_terms($post->ID,'portfolio_category');
        foreach ($myterms as $myterm ) {
         echo $myterm->slug."\n";
        }   
    ?> 

Which works fine as long as the portfolio item has a category. If it doesn't I get an error. Is there a way round this?

Thanks

share|improve this question

get_the_terms return and error on failure. So before your foreach loop check for the error and only run it if there is none, using is_wp_error.

<?php 
$myterms = get_the_terms( $post->ID, 'portfolio_category' );

if( !is_wp_error( $myterms ) )
    foreach( $myterms as $myterm )
        echo $myterm->slug . '<br />';
?> 
share|improve this answer
    
I really appreciate the response but I still get an error: Warning: Invalid argument supplied for foreach() – Chris Mooney Jul 17 '11 at 12:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.