Divi, custom function script returns "Attempt to read property ID on null" error, easy fix?
Divi, custom function script returns "Attempt to read property ID on null" error, easy fix?
So I have a question regarding a custom function I'm using on a Divi child theme to pull/display the Featured Image for any given page on the site.
It actually works, but a problem has arisen where, when I make a change on a page that is calling this function and then save, it returns the following error:
Warning: Attempt to read property "ID" on null in /home/customer/www/example.com/public_html/wp-content/themes/Divi-child/functions.php on line 30
Warning: Cannot modify header information - headers already sent by (output started at /home/customer/www/example.com/public_html/wp-content/themes/Divi-child/functions.php:30) in /home/customer/www/example.com/public_html/wp-admin/post.php on line 231
However, it saves properly and works when I reload the public-facing page. But like I said, it goes to a white page with this error on the back every time now when I save/preview and it makes me have to hit the back button to get to the edit page screen.
This happens on both PHP 8 and 8.1.
Is there a simple change I can make to the following code to fix this issue?
-------------------------------------------
// ADD SHORTCODE TO DISPLAY FEATURED IMAGE
function display_featured_image_shortcode($atts) {
global $post;
$default_atts = array(
'size' => 'thumbnail', // default image size
'class' => '', // default CSS class for the image
);
$atts = shortcode_atts($default_atts, $atts, 'featured_image');
if (has_post_thumbnail($post->ID)) {
$featured_image = get_the_post_thumbnail($post->ID, $atts['size'], array('class' => $atts['class']));
return $featured_image;
} else {
return ''; // return empty string if there's no featured image
}
}
add_shortcode('featured_image', 'display_featured_image_shortcode');
I tried changing PHP versions as I don't know anything else to try.
Thanks in advance!
Turbo Multi-language Translator
Make the better internet purchasing globaly
Turbosify SEO Speed Booster
5.0 (7)•Free plan available
Get better conversions by improving store loading speed
Installed
Turbo Multi-language Chat - AI Customer service in one hand