在 Woocommerce 单个产品页面中显示产品价格上方的自定义字段

Display a custom field above product price in Woocommerce single product pages

在 Woocommerce 中,我以正确的方式在支持的编辑产品页面中设置了一个自定义字段……现在我试图在将产品价格显示到单个产品页面之前显示此自定义字段值的产品。

但出于某种原因,使用下面的代码我可以显示它(而且产品价格也不显示):

function bd_rrp_price_html( $price, $product ) {

    echo get_post_meta( $post->ID, '_text_field', true );

}
add_filter( 'woocommerce_get_price_html', 'bd_rrp_price_html', 100, 2 );

感谢任何帮助

这是我想要在视觉上显示的内容:

已更新 (2 个备选方案)

请尝试使用以下重新访问的代码:

add_filter( 'woocommerce_get_price_html', 'custom_single_price_html', 100, 2 );
function custom_single_price_html( $price, $product ) {
    $custom_field = get_post_meta( $product->get_id(), '_text_field', true );
    if ( is_product() && ! empty($custom_field) )
        $price = '<span class="custom-textfield">' . $custom_field . '</span><br>' . $price;
    return $price;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。


或者您也可以使用以下方法:

add_filter( 'woocommerce_single_product_summary', 'single_product_text_field', 8 );
function single_product_text_field() {
    global $product;

    $custom_field = get_post_meta( $product->get_id(), '_text_field', true );
    if ( ! empty($custom_field) )
        echo '<p class="custom-textfield">' . $custom_field . '</p>';
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。