提问人:Okoma Victor 提问时间:10/15/2022 更新时间:10/16/2022 访问量:1043
请问我做错了什么,在 PHP 8 中收到未定义变量的通知
Please what Am i doing wrong, getting Notice of Undefined variable in PHP 8
问:
我在我的 WordPress 网站上收到一条警告消息,试图在第一段之后插入特色图片。它在 PHP7.4 中完美运行,没有警告或错误,但在 PHP 8.1 上出现以下警告
请提前感谢需要一些帮助。
警告:第 7 行的 /www/wwwroot/.../wp-content/themes/..../functions 中$post未定义的变量.php
警告:尝试在第 7 行的 /www/wwwroot/.../wp-content/themes/...../functions.php 中读取 null 上的属性“ID”
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 );
}
答:
1赞
amarinediary
10/16/2022
#1
您正在尝试通过之前未定义变量来访问该变量。$post
$post->ID
我们可以先通过 get_post()
获取 post 对象,然后检索 ID,但我们可以做得更好。我们可以使用 get_the_ID()
来检索帖子 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 );
评论
$post = get_post();