0

I have this error in my custom breadcrumbs : Notice: Trying to get property of non-object.

This is the code :

    $taxonomy_exists = taxonomy_exists($custom_taxonomy);
    if(empty($last_category) && !empty($custom_taxonomy) && $taxonomy_exists) {

        $taxonomy_terms = get_the_terms( $post, $custom_taxonomy );
        $cat_id = $taxonomy_terms[0]->term_id; // ERROR LINE
        $cat_nicename = $taxonomy_terms[0]->slug; // ERROR LINE
        $cat_link = get_term_link($taxonomy_terms[0]->term_id, $custom_taxonomy); // ERROR LINE
        $cat_name = $taxonomy_terms[0]->name;

    }

How i can solve this problem ?

1

You need to check if get_the_terms() is actually returning anything. If a post doesn't have terms in that taxonomy, then $taxonomy_terms won't actually have any terms in it. If $taxonomy_terms is empty then $taxonomy_terms[0] won't actually be a term object so trying to access a property on it (->term_id) will throw an error:

$taxonomy_exists = taxonomy_exists($custom_taxonomy);
if(empty($last_category) && !empty($custom_taxonomy) && $taxonomy_exists) {

    $taxonomy_terms = get_the_terms( $post, $custom_taxonomy );

    if ( ! empty( $taxonomy_terms ) ) {
        $cat_id = $taxonomy_terms[0]->term_id; // ERROR LINE
        $cat_nicename = $taxonomy_terms[0]->slug; // ERROR LINE
        $cat_link = get_term_link($taxonomy_terms[0]->term_id, $custom_taxonomy); // ERROR LINE
        $cat_name = $taxonomy_terms[0]->name;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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