【问题标题】:How to display custom field of a variation product in product page based on the attributes selected?如何根据选择的属性在产品页面中显示变体产品的自定义字段?
【发布时间】:2019-06-15 12:20:33
【问题描述】:

我为 woocommerce 中的每个变体产品设置了一个自定义字段。我想显示自定义字段来代替产品标题或页面的其他区域。因此,如果选择了变体,则希望显示变体子产品的自定义字段,否则显示父产品的自定义字段。 自定义字段应根据所选属性而更改。

目前我能够显示父产品的自定义字段,但子产品自定义字段不会根据选择的变化而改变。

如何设置自定义字段?

我尝试使用可视化编辑器在产品页面模板中设置自定义字段。但不适用于儿童产品。 我发现下面的代码可以在function.php中使用,似乎可以通过一些修改来满足我的需求

add_action( 'woocommerce_variation_options_pricing', 'add_custom_field_to_variations', 10, 3 );
function add_custom_field_to_variations( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input( array(
'id' => 'custom_field[' . $loop . ']',
'class' => 'short',
'label' => __( 'Custom Field', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'custom_field', true )
)
);
}

// 2. Save custom field on product variation save

add_action( 'woocommerce_save_product_variation', 'save_custom_field_variations', 10, 2 );
function save_custom_field_variations( $variation_id, $i ) {
$custom_field = $_POST['custom_field'][$i];
if ( isset( $custom_field ) ) update_post_meta( $variation_id,'custom_field', esc_attr( $custom_field ) );
}

// 3. Store custom field value into variation data

add_filter( 'woocommerce_available_variation', 'add_custom_field_variation_data' );
function add_custom_field_variation_data( $variations ) {
$variations['custom_field'] = '<div class="woocommerce_custom_field">Custom Field: <span>' . get_post_meta( $variations[ 'variation_id' ], 'custom_field', true ) . '</span></div>';
return $variations;
}

将以下代码添加到variation.php

<script type="text/template" id="tmpl-variation-template">
<div class="woocommerce-variation-description">
{{{ data.variation.variation_description }}}
</div>
 
<div class="woocommerce-variation-price">
{{{ data.variation.price_html }}}
</div>
 
<div class="woocommerce-variation-custom_field">
{{{ data.variation.custom_field}}}
</div>
 
<div class="woocommerce-variation-availability">
{{{ data.variation.availability_html }}}
</div>
</script>

1) 自定义字段在选择变体时显示在价格旁边。但我无法在产品页面的其他区域显示该字段。我确实通过简码添加了自定义字段,但它不会在选择变体时显示。

2) 我还希望在包含自定义字段的短代码的链接中使用(例如http://www.websitename.com/[product_metaname=custom_field]。父产品的自定义字段显示正常,但对于变体产品,它不会显示或更新变体选择。

引用自

https://businessbloomer.com/woocommerce-add-custom-field-product-variation/?unapproved=224924&moderation-hash=de32083fe8b29ba15adaf268926fdd83#comment-224924

https://wordpress.stackexchange.com/questions/276941/woocommerce-add-extra-field-to-variation-product?rq=1

【问题讨论】:

    标签: php jquery wordpress woocommerce


    【解决方案1】:

    为什么不使用变化价格?可以为每个变化设置价格。 在此 WooCommerce 文档 articlesection 中查看此图像

    也许您有一个特殊的用例,您需要使用自定义字段。在这种情况下,我建议您检查此class 并使用正确的钩子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      • 2018-06-12
      相关资源
      最近更新 更多