在 HTML 标签之外呈现的 ACF 字段

ACF Fields Rendered Outside of HTML Tags

我正在使用 ACF 并为我的产品设置了一个名为 product_title 的字段。

我正尝试在我的 functions.php 文件中使用 WooCommerce 挂钩在我的产品页面上显示此自定义字段。

function hom_add_product_header()
{
    $product_title  = the_field('product_title');
    ?>

    <h1><?php echo $product_title; ?></h1>

    <?php
}
add_filter('woocommerce_single_product_summary', 'hom_add_product_header', 5);

但是当我查看呈现的页面时,product_title 呈现在空 <h1></h1> 标签之外!

我也试过这样的输出缓冲...

function hom_add_product_header()
{
    # Add the start
    ob_start();

    $product_title  = the_field('product_title');
    ?>

    <h1><?php echo $product_title; ?></h1>

    <?php
    # Fetch the cache
    $data = ob_get_contents();
    # End and clear the buffer
    ob_end_clean();
    # Send data back for render
    return $data;
}
add_filter('woocommerce_single_product_summary', 'hom_add_product_header', 5);

但是使用此代码根本不会显示任何内容!

为什么我的内容没有在 HTML 标签内呈现?

这应该有效:

function hom_add_product_header()
{
    $product_title  = get_field('product_title');
    echo "<h1>" . $product_title . "</h1>"
}

php脚本从上到下解析,每个非php部分在解析时直接渲染。由于您在声明后几行调用函数,因此解析器会看到 <h1></h1> 标记并呈现它们。之后渲染器到达函数调用并执行该函数。关键部分是您正在破坏函数内的 php 控制流。