Reputation: 91
I've been asked to add some custom fields to a woocommerce site we designed. I've added them using the meta: field in the CSV import tool and it has successfully imported the info into the product page as a custom field.
The difficult part is, I want to be able to display the custom field on the product page, I've checked the documentation and online forums without much luck.
How can I display the custom field value under the product excerpt in single product pages?
Any help is appreciated
Upvotes: 3
Views: 3820
Reputation: 253804
As this custom fields data are product post meta data (located in wp_postmeta
database table), you have 2 alternatives to get the meta values using:
get_meta()
WC_Data
method on the WC_Product
product object (the best way using new CRUD methods introduced with Woocommerce 3).get_post_meta()
dedicated function from the product ID (the old way)The following code will display your custom field after the product short description. You will need to replace in the code _custom_meta_key
by your real meta key slug:
// Display a product custom field after product short description
add_action( 'woocommerce_single_product_summary', 'display_product_custom_field', 25 );
function display_product_custom_field(){
global $product;
$value = $product->get_meta('_custom_meta_key', true );
// OR
// $value = get_post_meta( $product->get_id(), '_custom_meta_key', true );
if( ! empty( $value ) )
echo '<p>'.__('My value', 'woocommerce') . ': ' . $value . '</p>';
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Upvotes: 2
Reputation: 46
You can use a WooCommerce hook in your functions.php if you don't want to copy and customize a WooCommerce template file into your own theme:
// Add ACF field data to Product page
add_action( 'woocommerce_after_single_product_summary', 'my_acf_product_content', 10 );
function my_acf_product_content() {
$test_field = get_field( 'test_field' );
if ( $test_field ) {
echo '<h3>ACF Content Header</h3>';
echo '<div>' . $test_field . '</div>';
}
}
For reference on where you want to output the field data on the product page (in the example case "woocommerce_after_single_product_summary"), you can refer to this link, which I believe should still be relevant: https://businessbloomer.com/woocommerce-visual-hook-guide-single-product-page
Upvotes: 1
Reputation: 103
Why dont you try editing the file in woocommerce: single-product.php or content-single-product.php
Then use advanced custom fields to display your content - https://www.advancedcustomfields.com/resources/text/
<h2><?php the_field('text'); ?></h2>
Upvotes: 0