Error on same place Trying to get property of non-object WordPress

I created a function that returns an array of Custom Post type taxonomies:

function arfolio_get_cpt_tax(){

    $categories = get_terms( 'service_categories' );
    $cat_array = array();

    foreach( $categories as $cat ){
        $cat_array[$cat->term_id] = $cat->name;
    }

    return $cat_array;

}

I call this function in page.php. It’s working fine. But When I am calling this function another file which is included in functions.php It’s getting me error:

Read More
Notice: Trying to get property of non-object in wordpresswp-contentthemesarfolio-wpinccpt.php on line 127

Please help me to fix this error.

The line 127 is in the above function:

$cat_array[$cat->term_id] = $cat->name;

Thanks

Related posts

Leave a Reply

2 comments

  1. Check that $categories is an array of object, to show it, put the following code:

    function arfolio_get_cpt_tax(){
    
        $categories = get_terms( 'service_categories' );
    
        // See the var
        var_dump($categories); die();
    
        $cat_array = array();
    
        foreach( $categories as $cat ){
            $cat_array[$cat->term_id] = $cat->name;
        }
    
        return $cat_array;
    
    }
    

    It should shows you an objects array, if not, check what is the answer of the function, maybe is an array of arrays, and you should use something like:

    function arfolio_get_cpt_tax(){
    
        $categories = get_terms( 'service_categories' );
        $cat_array = array();
    
        foreach( $categories as $cat ){
            $cat_array[ $cat['term_id'] ] = $cat['name'];
        }
    
        return $cat_array;
    
    }
    
  2. get_terms return WP_Error object if it did not success please do

    var_dump($categories); die();
    

    and check the error
    it may be something like this

    object(WP_Error)[196]
      public 'errors' => 
        array (size=1)
          'invalid_taxonomy' => 
            array (size=1)
              0 => string 'Invalid taxonomy' (length=16)
      public 'error_data' => 
        array (size=0)
          empty
    

    if so please check that your taxonomy is exist

    Edit

    it’s a case of your term fetching occurring before the taxonomy has been registered.

    please check that you call your function after the that the taxonomy is registered
    for example check that you include your file which calling the function is included after the registration of the taxonomy

    I assume that you registered your taxonomy in the init action and the init action is called actually after the functions.php is included so any call of your function inside functions.php will not work
    so you need to use this function inside templates or in template parts