phpwordpresswoocommercecustom-fields

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


In Woocommerce I have set a custom field in backed edit product pages in a correct way… Now I am trying to display a product this custom field value, before product price into a single product pages.

But for some reason, with the code below I can get it displayed (and the product price neither):

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 );

Any help is appreciated

This is what I want visually to be displayed:

showing the issue with image


Solution

  • Updated (2 alternatives)

    Try instead the following revisited code:

    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;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.


    Or alternatively you can also use the following:

    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>';
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.