I got a Warning message on my WordPress site trying to insert a featured image after the first paragraph. It worked perfectly without warning or error in PHP7.4 but got the below warning on PHP 8.1
Please would need some help thanks in advance.
Warning: Undefined variable $post in /www/wwwroot/.../wp-content/themes/..../functions.php on line 7
Warning: Attempt to read property "ID" on null in /www/wwwroot/.../wp-content/themes/...../functions.php on line 7
add_filter( 'the_content', 'insert_featured_image', 20 );
function insert_featured_image( $content ) {
$feat_img = get_the_post_thumbnail($post->ID, 'post-single');
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( '<div class="top-featured-image">' . $feat_img . '</div>', 1, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
You're trying to access a $post
variable through $post->ID
tho you didn't define it before.
We could first fetch the post object through get_post()
then retrieve the ID, but we can do better. We can use get_the_ID()
to retrieve the post ID.
<?php
add_filter( 'the_content', function ( $content ) {
if ( ! is_admin() && is_single() ) {
$thumbnail = get_the_post_thumbnail( get_the_ID(), 'post-single' );
return prefix_insert_after_paragraph( '<div class="top-featured-image">' . $thumbnail . '</div>', 1, $content );
};
return $content;
}, 20 );