【问题标题】:Add a custom field value below product title in WooCommerce archives pages在 WooCommerce 档案页面的产品标题下方添加自定义字段值
【发布时间】:2018-07-04 19:14:44
【问题描述】:

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

但我不知道如何将自定义字段连接到产品的显示, 因此自定义字段的文本将显示在产品标题下方。

如何在产品标题下方显示自定义字段

【问题讨论】:

    标签: php wordpress woocommerce product custom-fields


    【解决方案1】:

    更新:

    试试这个自定义挂钩函数,它将在产品标题下方显示您的自定义字段值:

    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 文件中。

    它应该可以工作。

    【讨论】:

      【解决方案2】:

      对于任何试图实现这一点的人,函数 woocommerce_product_custom_fields() 中缺少结束 div。添加回声'';在结束大括号之前,否则产品设置中的所有其他产品数据选项卡都将为空。

      【讨论】:

      • 请尝试使用一些代码改进您的答案。它将对未来的用户更有用。
      【解决方案3】:

      如果您尝试使用此代码,则关闭 div 需要:

      echo '&lt;/div&gt;';

      否则echo '&lt;div class="product_custom_field"&gt;'; 保持打开状态。

      【讨论】:

        猜你喜欢
        • 2019-08-11
        • 1970-01-01
        • 2014-07-12
        • 2021-07-12
        • 1970-01-01
        • 2020-12-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多