簡體   English   中英

在 WooCommerce 檔案頁面中的產品標題下方添加自定義字段值

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

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

代碼位於活動子主題(或活動主題)的 function.php 文件中。

它應該工作。

對於任何試圖實現這一點的人來說,函數 woocommerce_product_custom_fields() 中缺少結束 div。 添加回聲''; 在結束大括號之前,否則產品設置中的所有其他產品數據選項卡都將為空。

如果您嘗試使用此代碼,則結束 div 需要是:

echo '</div>';

否則echo '<div class="product_custom_field">'; 保持開放。

暫無
暫無

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

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