210 posts
  • Has sold $40,000+ on Envato Market
  • Sells items exclusively on Envato Market
  • Has referred 1+ members
  • Has collected 1+ items on Envato Market
+2 more
codeex says

Hi,

I’m wondering why this get_terms not working as an array, what did I miss? anyone can help :)

$taxonomy = 'tax_type';
    $terms = get_terms( $taxonomy, array( 'hide_empty' => 0 ) );
    $wp_terms = array();
    foreach ($terms as $term) {
       $wp_terms[$term->term_id] = $term->name;
    }
    array_unshift( $wp_terms, "Choose a term" );

it says “Notice: Trying to get property of non-object in ….. “

thanks

422 posts Keep Walking
  • Has been part of the Envato Community for over 3 years
  • Elite Author: Sold more than $75,000 on Envato Market
  • Has sold $125,000+ on Envato Market
  • Has collected 100+ items on Envato Market
+2 more
UXbarn says

I guess the returned array is empty? So when you are trying to get the value of the “term_id” property (or the others) from the empty object, it throws the error message.

Try using the if block to check before the foreach as:

if ( !empty( $terms ) && !is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
...
}
}

More info here: http://codex.wordpress.org/Function_Reference/get_terms :)

210 posts
  • Has sold $40,000+ on Envato Market
  • Sells items exclusively on Envato Market
  • Has referred 1+ members
  • Has collected 1+ items on Envato Market
+2 more
codeex says

Thanks man.. I will try this later..

210 posts
  • Has sold $40,000+ on Envato Market
  • Sells items exclusively on Envato Market
  • Has referred 1+ members
  • Has collected 1+ items on Envato Market
+2 more
codeex says

I added the given code above and it fixed the error but no terms is being displayed..

210 posts
  • Has sold $40,000+ on Envato Market
  • Sells items exclusively on Envato Market
  • Has referred 1+ members
  • Has collected 1+ items on Envato Market
+2 more
codeex says

it says “Invalid Taxonomy”..

$taxonomy = 'tax_name';
   $terms = get_terms( $taxonomy, array( 'hide_empty' => 0 ) );
   $wp_terms = array();

   echo '<pre>' . print_r( $terms, true ) . '</pre>';
   echo '<hr />';

   if ( !empty( $terms ) && !is_wp_error( $terms ) ) {
        foreach ($terms as $term) {
           $wp_terms[$term->term_id] = $term->name;
        }
     }

     echo '<pre>' . print_r( $wp_terms, true ) . '</pre>';
   array_unshift( $wp_terms, "Choose a term" ); 

not sure why it got Invalid Taxonomy..

422 posts Keep Walking
  • Has been part of the Envato Community for over 3 years
  • Elite Author: Sold more than $75,000 on Envato Market
  • Has sold $125,000+ on Envato Market
  • Has collected 100+ items on Envato Market
+2 more
UXbarn says
by
by
by
by
by
by