0

get_queried_object returns NULL inside a function hooked to wp_enqueue_scripts action hook when going to an nonexistent category URL on my website. If the category exists, the error is not shown and I think it does not exist.

I need it to conditionally load a CSS file for better modularization, not in the admin area but for the end-user.

What is the correct way to do this?

The error shown in the HTML:

Notice: Trying to get property 'term_id' of non-object in /var/www/html/wp-content/themes/custom-theme/functions.php on line 193

The code starting at line 193:

if (get_queried_object()->term_id === 3 ||
        (count(get_the_category()) > 0 && get_the_category()[0]->slug == 'arta')) {
    wp_enqueue_style( 'twentytwenty-style-2', get_stylesheet_directory_uri() . '/style-arta.css', array(), $theme_version );
}

2 Answers 2

3

I agreed with @PatJ — you should check if get_queried_object() returns an object or not.

But you could simplify your code by simply using is_category() and in_category() which are conditional tags in WordPress:

if ( is_category( 3 ) || in_category( 'arta' ) ) {
    wp_enqueue_style( 'twentytwenty-style-2', get_stylesheet_directory_uri() . '/style-arta.css', array(), $theme_version );
}
1

According to the documentation, get_queried_object() is a wrapper for WP_Query::get_queried_object(), which will return null if there's no such object.

A simple way to check that you've got a non-null return is using empty():

$object = get_queried_object();
if ( 
    ! empty( $object) &&
    ( 
        $object->term_id === 3 ||
        (
            count( get_the_category() ) > 0 &&
            get_the_category()[0]->slug == 'arta'
        )
    ) 
) {
    wp_enqueue_style( 'twentytwenty-style-2', get_stylesheet_directory_uri() . '/style-arta.css', array(), $theme_version );
}
2
  • This misses the problem. The issue is not that get_queried_object() is missing. The issue is that when they are not viewing term archives then get_queried_object() is not returning WP_Term, meaning that get_queried_object()->term_id doesn't exist, even though get_queried_object() is not empty. Commented Mar 21, 2021 at 10:43
  • Maybe I wasn't sufficiently clear. My logic was this: The PHP notice says Trying to get property 'term_id' of non-object. get_queried_object() will return an object (WP_Term, WP_Post, WP_Post_Type, or WP_User) or null. I assumed that, given the options, OP is getting back the null value. empty( NULL ) will be true.
    – Pat J
    Commented Mar 21, 2021 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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