Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I wanted to display product category,in product catalog on my WooCommerce site.I asked another question earlier to make this code working.I added this code on my content-product.php file.

    <?php
   $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
   $parents = get_the_terms($term->parent, get_query_var('taxonomy') );

   echo "<div class='product-cat'>";
   echo "In"." "." ";
   foreach( $parents as $parent ) {
   echo '<a href="'.get_term_link($parent).'">'.$parent->name.'</a>';
    }
  echo "</div>";
  ?>

Everything is working perfectly on product catalog,but whenever i do a search i am getting this error " Invalid argument supplied for foreach()" .

I am not that good with programming,i managed make the code working for product catalogs but it is not working with search.Please if anyone can help me,it will be greatly appreciated.

share|improve this question
add comment

1 Answer

" Invalid argument supplied for foreach()" . means that the $parents variable is not an array so you can't loop through it. You should wrap the foreach loop in an if check that verifies that $parents is something valid.

<?php
   $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
   $parents = get_the_terms($term->parent, get_query_var('taxonomy') );

   if( $parents && ! is_wp_error($parents) ) :

     echo "<div class='product-cat'>";
     echo "In"." "." ";
     foreach( $parents as $parent ) {
      echo '<a href="'.get_term_link($parent).'">'.$parent->name.'</a>';
     }
     echo "</div>";

   endif;

?>

Though secondarily.... get_query_var('term') and get_query_var('taxonomy') are not returning anything on the search page because those query vars don't pertain to the search query.

share|improve this answer
    
Thanks for answering,can you tell me which functions should i use for search page instead get_query_var(). –  user946131 Apr 3 '13 at 22:37
    
That depends. I can't really tell what you are trying to do. Could you edit your question? –  helgatheviking Apr 4 '13 at 9:27
add comment

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.