如何根据所选属性在产品页面中显示变化产品的自定义字段?

时间:2019-06-15 12:20:33

标签: php jquery wordpress woocommerce

我为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;
}

将以下代码添加到variant.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_meta name = 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

1 个答案:

答案 0 :(得分:0)

为什么不使用变动价格?可以为每个变化设置价格。 请参见本WooCommerce文档Set variation product price of $50

section中的图片article

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