0

Please help!

I updated my php to 8.0 and my WordPress install to the current version (6.7.1), and now get the following warning messages on my site:

Warning: Undefined variable $post in /home/thespace/public_html/wp-content/themes/mon-cahier/functions.php on line 170
Warning: Attempt to read property "ID" on null in /home/thespace/public_html/wp-content/themes/mon-cahier/functions.php on line 170

Here is the PHP for line 170:

if ( is_singular() && wp_attachment_is_image ( $post->ID ) ) global $post; { wp_enqueue_script( 'keyboard-image-navigation', get_stylesheet_directory_uri() . '/js/keyboard-image-navigation.js', array( 'jquery' ), '20120202' ); } } add_action( 'wp_enqueue_scripts', 'mon_cahier_scripts' ); 

How can I fix this and get rid of these warnings on my site?

    1 Answer 1

    2

    As the warnings say, $post is used but not defined, hence "Undefined variable $post" and then 'Attempt to read property "ID" on null'. It seems like the global $post is in an erroneous location and should be before the if statement:

    global $post; if ( is_singular() && wp_attachment_is_image ( $post->ID ) ) 

    You may also wish to guard against the case of if $post is empty, using the nullsafe operator:

    if ( is_singular() && wp_attachment_is_image ( $post?->ID ) ) 

    Or perhaps better yet, do the is_singular() check before accessing $post at all, since $post should be defined if is_singular() is true:

    if ( is_singular() ) { global $post; if ( wp_attachment_is_image( $post->ID ) ) { wp_enqueue_script( 'keyboard-image-navigation', get_stylesheet_directory_uri() . '/js/keyboard-image-navigation.js', array( 'jquery' ), '20120202' ); 

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.