【问题标题】:Display custom field blow product title Woocommerce product single pages显示自定义字段打击产品标题 Woocommerce 产品单页
【发布时间】:2020-12-04 02:15:40
【问题描述】:

我想在后端 Woocommerce 产品页面中添加一个文本字段,并在产品标题下方的前端显示/回显文本。

现在我有“自定义字段框”来在后端编写文本(见截图),但我不知道如何在前端显示文本。有人可以帮我处理这段代码吗?

我关注了这个页面,但它只适用于存档页面...... Add a custom field value below product title in WooCommerce archives pages

提前谢谢你!

杰瑞

函数.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));
}

【问题讨论】:

  • 我认为这里的问题是选择正确的挂钩位置。
  • 请对以下答案提供一些反馈,我们将不胜感激。谢谢。

标签: php wordpress woocommerce product hook-woocommerce


【解决方案1】:

您的解决方案是正确的钩子,当您使用 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”并放置您想要的正确钩子。 这是一篇很棒的文章,它显示了每个位置的位置和所需的钩子。告诉我你得到了什么!

【讨论】:

    【解决方案2】:

    添加以下内容以在产品标题下方的单个产品页面中显示该产品自定义字段:

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

    代码在您的活动子主题(或活动主题)的functions.php 文件中。它应该可以工作。

    然后它将调用您已经在使用的函数,以在产品存档页面上显示自定义字段:

    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 action hooks and overriding templates

    【讨论】:

      猜你喜欢
      • 2017-11-16
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 2021-09-23
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多