如何在 wordpress WooCommerce 中的产品标题下方添加自定义字段文本

How to add a custom field text below the product title in wordpress WooCommerce

在 WooCommerce 中,我想将自定义文本添加到我的产品显示中,该文本将从产品编辑页面的自定义字段中获取。

现在是这样的:

您可以在下面看到带有标题的产品:

Website link

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

您需要将完整代码添加到主题的 'functions.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'
        )
    );
    echo '</div>';
}

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));
    // Custom Product Number Field
    $woocommerce_custom_product_number_field = $_POST['_custom_product_number_field'];
    if (!empty($woocommerce_custom_product_number_field))
        update_post_meta($post_id, '_custom_product_number_field', esc_attr($woocommerce_custom_product_number_field));
    // Custom Product Textarea Field
    $woocommerce_custom_procut_textarea = $_POST['_custom_product_textarea'];
    if (!empty($woocommerce_custom_procut_textarea))
        update_post_meta($post_id, '_custom_product_textarea', esc_html($woocommerce_custom_procut_textarea));
}

您的自定义字段 ID 在这里是 _custom_product_text_field,您可以在产品模板的循环中显示像 <?php echo get_post_meta($post->ID, '_custom_product_text_field', true); ?> 这样的数据(可能覆盖 'woocommerce/single-product.php')。

如果更新 'functions.php' 时 WordPress returns 出错,请尝试通过 FTP 上传或使用一些文件管理器插件。