php - Wordpress generating Undefined Variable warning

admin2025-01-07  4

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?

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?

Share Improve this question edited Dec 31, 2024 at 3:10 Wongjn 5551 silver badge7 bronze badges asked Dec 30, 2024 at 19:19 stacystacy 1
Add a comment  | 

1 Answer 1

Reset to default 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' );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736254521a213.html

最新回复(0)