add Custom text field in single product page

I am working on a project in woocommerce.

Can anyone help me to add a custom text field next to “add to cart”?

Read More

I tried the following but it is not working.

add_action( 'woocommerce_after_single_product_summary', 'add_custom_field', 0 );

function add_custom_field() {
    global $post;

    echo "<div class='prod-code'>Product Code: ";
    $text= get_field('txt-field', $post);
    echo "</div>";

    return true;
}

Related posts

Leave a Reply

3 comments

  1. Perhaps try using $post->ID like this:

    add_action( 'woocommerce_after_single_product_summary', 'add_custom_field', 0 );
    
    function add_custom_field() {
        global $post;
    
        echo "<div class='prod-code'>Product Code: ";
        $text= get_field('txt-field', $post->ID);
        echo "</div>";
    
        return true;
    }
    
  2. put your html code inside content-product.php (wp-content/themes/YOUR THEME/woocommerce/content-product.php)
    content-product.php contains code of list page in wordpress. if you want to edit product page than edit content-single-product.php.

  3. You are using Woocommerce there are two case :

    1. You are reading post ID
    2. You want to display a SKU

    You can implement it via single function :

    add_action( 'woocommerce_single_product_summary', 'display_productCode', 5 );
    function display_productCode(){
        global $product;
        echo 'SKU: ' . $product->get_sku();
        echo 'Product ID:'.$product->get_id();
    
    }