0

我正在使用 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 标签内呈现?

4

1 回答 1

1

这应该有效:

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

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

于 2018-03-14T15:19:57.127 回答