Updated:
我重新审视了你的代码,简化了事情,删除了不必要的代码。我添加了必要的代码,以使此“雕刻字段”仅在选中复选框设置选项时才显示在单个产品页面上。
对于你的最后一个问题,请在最后检查(对于没有复选框设置的产品类别).
这是代码:
// Display Fields
add_action('woocommerce_product_options_general_product_data', 'product_custom_fields_add');
function product_custom_fields_add(){
global $post;
echo '<div class="product_custom_field">';
// Custom Product Checkbox Field
woocommerce_wp_checkbox( array(
'id' => '_engrave_text_option',
'desc' => __('set custom Engrave text field', 'woocommerce'),
'label' => __('Display custom Engrave text field', 'woocommerce'),
'desc_tip' => 'true'
));
echo '</div>';
}
// Save Fields
add_action('woocommerce_process_product_meta', 'product_custom_fields_save');
function product_custom_fields_save($post_id){
// Custom Product Text Field
$engrave_text_option = isset( $_POST['_engrave_text_option'] ) ? 'yes' : 'no';
update_post_meta($post_id, '_engrave_text_option', esc_attr( $engrave_text_option ));
}
add_action( 'woocommerce_before_add_to_cart_button', 'add_engrave_text_field', 0 );
function add_engrave_text_field() {
global $post;
// If is single product page and have the "engrave text option" enabled we display the field
if ( is_product() && get_post_meta( $post->ID, '_engrave_text_option', true ) == 'yes' ) {
?>
<div>
<label class="product-custom-text-label" for="engrave_text"><?php _e( 'Engraving option:', 'woocommerce'); ?><br>
<input style="min-width:220px" type="text" class="product-counter" name="engrave_text" placeholder="<?php _e( 'Enter Your Custom Letters ...', 'woocommerce'); ?>" maxlength="3" />
</label>
</div><br>
<?php
}
}
代码位于活动子主题(或主题)的 function.php 文件中或任何插件文件中。
经过测试并有效。
复选框输出并保存:以编程方式添加数据选项选项卡到管理产品页面 Metabox
在产品设置中选中复选框选项后,您将看到类似以下内容:
让它起作用对于产品类别或产品标签 (没有设置复选框):
add_action( 'woocommerce_before_add_to_cart_button', 'add_engrave_text_field', 0 );
function add_engrave_text_field() {
global $post;
// HERE set the term Ids, slug or name (or an array of values)
$categories = array( 'clothing', 'music' );
$taxonomy = 'product_cat'; // (For product tags use 'product_tag' instead)
// If is single product page and have the "engrave text option" enabled we display the field
if ( is_product() && has_term( $categories, 'product_cat', $post->ID ) ) {
?>
<div>
<label class="product-custom-text-label" for="engrave_text"><?php _e( 'Engraving option:', 'woocommerce'); ?><br>
<input style="min-width:220px" type="text" class="product-counter" name="engrave_text" placeholder="<?php _e( 'Enter Your Custom Letters ...', 'woocommerce'); ?>" maxlength="3" />
</label>
</div><br>
<?php
}
}
代码位于活动子主题(或主题)的 function.php 文件中或任何插件文件中。
经过测试并有效。