【发布时间】: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]。父产品的自定义字段显示正常,但对于变体产品,它不会显示或更新变体选择。
引用自
【问题讨论】:
标签: php jquery wordpress woocommerce