簡體   English   中英

顯示自定義字段吹產品標題Woocommerce產品單頁

[英]Display custom field blow product title Woocommerce product single pages

我想在后端 Woocommerce 產品頁面中添加一個文本字段,並在產品標題下方的前端顯示/回顯文本。

現在我有“自定義字段框”在后端編寫文本(見截圖),但我不知道如何在前端顯示文本。 有人可以幫我處理這段代碼嗎?

我關注了此頁面,但僅適用於存檔頁面... 在 WooCommerce 存檔頁面的產品標題下方添加自定義字段值

先感謝您!

傑瑞

功能.php

        // 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));
}

您的解決方案是正確的鈎子,當您使用 add_action() 時,您需要選擇正確的鈎子以將代碼插入正確的位置。

可能您想要的位置是“woocommerce_before_add_to_cart_form”;

add_action('woocommerce_before_add_to_cart_form', 'woocommerce_product_custom_fields');

我不確定確切的位置,但您可以更改“woocommerce_before_add_to_cart_form”並放置您想要的正確鈎子。 這是一篇很棒的文章,它顯示了每個位置的位置和所需的鈎子。 讓我知道你得到了什么!

添加以下內容以在產品標題下方的單個產品頁面中顯示該產品自定義字段:

add_action( 'woocommerce_single_product_summary', 'custom_field_display_below_title', 7 );

代碼進入您的活動子主題(或活動主題)的functions.php 文件。 它應該工作。

然后它將調用您已經在使用的 function 以在產品存檔頁面上顯示自定義字段:

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>';
    }
}

相關: WooCommerce 動作掛鈎和覆蓋模板

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM