Add a custom field value below product title in WooCommerce archives pages

时光毁灭记忆、已成空白 提交于 2019-11-30 18:01:17

问题


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.



来源:https://stackoverflow.com/questions/48444564/add-a-custom-field-value-below-product-title-in-woocommerce-archives-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!