简体   繁体   中英

Displaying custom field values after product short description in Woocommerce

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

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:

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.

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM