警告:更新到 PHP 7.2 后,使用未定义的常量 _ - 假设为“_”(这将在 PHP 的未来版本中引发错误)

问题描述 投票:0回答:3

我已经检查了其他相关帖子,但不幸的是它对我的问题没有帮助。

我正在

警告:使用未定义的常量 _ - 假定为“_”(这将在 PHP 的未来版本中引发错误)

更新到 PHP 7.2 版本后出现错误

我将原因追溯到这段代码片段:

<span class="post-container__excerpt-price"><?php echo '$' . number_format( (float)get_field('price', $post->ID) );  ?></span>

当我删除此错误时,错误消失了,但我似乎也找不到此代码的任何明显问题。

'price', $post->ID
指的是使用 ACF 创建的自定义字段。

有人有什么想法吗? 非常感谢!

整个代码块如下:

// create shortcode to list all listings
add_shortcode( 'list-posts-basic', 'rmcc_post_listing_shortcode1' );
function rmcc_post_listing_shortcode1( $atts ) {
    ob_start();
    $query = new WP_Query( array(
        'post_type' => 'listings',
        'posts_per_page' => -1,
        'order' => 'DESC',
        'orderby' => 'date',
    ) );
    if ( $query->have_posts() ) { ?>
        <div class="posts-container">
            <?php while ( $query->have_posts() ) : $query->the_post(); ?>
            <div class="post-container" id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

                <a class="" href="<?php the_permalink(); ?>"><div class="listing-post-img" style="background: url(<?php echo get_the_post_thumbnail_url() ?> )"></div></a>

                <div class="post-container__content">
                    <a href="<?php the_permalink(); ?>"><h3><?php the_title(); ?></h3></a>
                    <p class="post-container__excerpt">
                        <?php the_excerpt();  ?>
                        <span class="post-container__excerpt-price"><?php echo '$' . number_format( (float)get_field('price', $post->ID) );  ?></span>
                    </p>

                    <a class="post-container__button" href="<?php the_permalink(); ?>">View Details</a>
                </div>
            </div>
            <?php endwhile;
            wp_reset_postdata(); ?>
        </div>
    <?php $myvariable = ob_get_clean();
    return $myvariable;
    }
}
php wordpress advanced-custom-fields
3个回答
0
投票

问题是$post->ID。此时全球 $post 无法访问。

您需要添加全局$post;或者你可以交换 get_the_ID() 来代替它。

您也可以缩短它。

<?php $myvariable = ob_get_clean();
    return $myvariable;
    }

简短版本,因为没有理由只声明一个变量只是为了返回。

<?php return ob_get_clean();
}

使用 $post->ID 进行测试


0
投票

您只需插入以下代码:

return ob_get_clean();

如果您的代码是:

.....
...
..

做:

return ob_get_clean();

对我来说效果很好。


0
投票

我想我发现了导致这个确切错误的问题

undefined constant _ - assumed '_'
。 PHP 7 似乎对
<?php
?>
之前或之后的空格非常挑剔。它之所以引用“未定义常量”
_
,是因为字符
_
可能是 Unicode 字符。在我的例子中,它是不间断空格的 Unicode,并且它恰好位于
?>
之前。

在您的代码中,您说它在这一行上 - 请注意

?>
:

之前的两个空格
<span ...><?php echo ...get_field('price', $post->ID) );  ?></span>

我敢打赌第二个空格实际上是一个 Unicode 字符,这就是导致警告的原因。就我而言,用实际空间覆盖它解决了问题,即使它看起来完全相同。我通过在十六进制编辑器中打开它来确认我的字符是 Unicode 字符,该编辑器将“空格”显示为 0xC2A0,而不是通常的 0x20。我也检查了你的,但我的猜测是,当将其粘贴到此网站时,它已转换为实际空间。

更多信息:

MIME 编码、带引号的可打印文本中的“=C2=A0”是什么?

警告:无法修改标头信息 - 标头已发送

© www.soinside.com 2019 - 2024. All rights reserved.