Add a custom field value below product title in Wo

2019-04-12 13:58发布

问题:

In WooCommerce I would like to add custom text to my products display, that will be grabbed from a custom field in product's edit page.

This is how it looks now:

You can see the products with their title below:

I would like to add a text below every product, marked with blue pen:

I have managed to find some custom php code to add custom field in product's page like this:

.

This is my code:

    // Display Fields
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields');

// Save Fields
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');

function woocommerce_product_custom_fields()
{
    global $woocommerce, $post;
    echo '<div class="product_custom_field">';
    // Custom Product Text Field
    woocommerce_wp_text_input(
        array(
            'id' => '_custom_product_text_field',
            'placeholder' => 'Custom Product Text Field',
            'label' => __('Custom Product Text Field', 'woocommerce'),
            'desc_tip' => 'true'
        )
    );

}

function woocommerce_product_custom_fields_save($post_id)
{
    // Custom Product Text Field
    $woocommerce_custom_product_text_field = $_POST['_custom_product_text_field'];
    if (!empty($woocommerce_custom_product_text_field))
        update_post_meta($post_id, '_custom_product_text_field', esc_attr($woocommerce_custom_product_text_field));
}

But I don't know how to connect the custom field to the product's display, so the custom field's text will be shown below the product's title.

How to display the custom field below product title

回答1:

Updated:

Try this custom hooked function, that will display your custom field value below product title:

add_action( 'woocommerce_after_shop_loop_item_title', 'custom_field_display_below_title', 2 );
function custom_field_display_below_title(){
    global $product;

    // Get the custom field value
    $custom_field = get_post_meta( $product->get_id(), '_custom_product_text_field', true );

    // Display
    if( ! empty($custom_field) ){
        echo '<p class="my-custom-field">'.$custom_field.'</p>';
    }
}

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

It should work.



回答2:

For anyone trying to implement this, the closing div is missing from function woocommerce_product_custom_fields(). Add echo ''; before the closing curly bracket otherwise all of the other product data tabs in the product settings will be empty.