2017-11-25 174 views
0

我正在使用所选购物平台的WordPress电子商务网站上工作; WooCommerce。为什么WooCommerce自定义复选框在取消选择时不删除“附加的”PHP编码?

我已经创建了一个自定义复选框,则WooCommerce产品仪表板内,通过将下面的代码到functions.php文件:

function product_custom_fields_add(){ 

    global $post; 

    $input_checkbox = get_post_meta($post->ID, '_engrave_text_option', true); 
    if(empty($input_checkbox) || $input_checkbox == 'no') $input_checkbox = ''; 

     echo '<div class="product_custom_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', 
      'value'  => $input_checkbox 
     ) 
    ); 

echo '</div>'; 
} 
add_action('woocommerce_product_options_advanced', 'product_custom_fields_add'); 

要保存自定义字段的值,我已插入下面的代码为functions.php文件:

function woocommerce_product_custom_fields_save($post_id){    
    $_engrave_text_option = isset($_POST['_engrave_text_option']) ? 'yes' : 'no'; 
    update_post_meta($post_id, '_engrave_text_option', $_engrave_text_option);  
} 
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save'); 

的想法是,当一个网站管理选中该复选框,它会触发下面的代码,以便在产品页面创建一个自定义文本框:

function add_engrave_text_field() { 
    global $post; 

    // Get the checkbox value 
    $engrave_option = get_post_meta($post->ID, '_engrave_text_option', true); 

    // If is single product page and have the "engrave text option" enabled we display the field 
    if (is_product() && ! empty($engrave_option)) { 

     ?> 
     <div> 
      <label class="product-custom-text-label" for="engrave_text"><?php _e('Custom Letters:', 'woocommerce'); ?><br> 
       <input style="min-width:220px" type="text" class="product-counter" name="engrave_text" placeholder="<?php _e('Enter Your Custom Letters ...', 'woocommerce'); ?>" minlength="<?php global $post; echo get_post_meta($post->ID,'_minimum_engrave_text_option',true);?>" maxlength="<?php global $post; echo get_post_meta($post->ID,'_maximum_engrave_text_option',true);?>" /> 
      </label> 
     </div><br> 
<?php 
    } 
} 
add_action('woocommerce_before_add_to_cart_button', 'add_engrave_text_field', 0); 
?> 

上述代码在选择复选框时可以在产品页面上创建自定义文本字段。出现问题的地方在于,取消选中复选框时,自定义文本框会保留在产品页面上。

是否有人能够看到我在哪里出错?

回答

1

这里缺少点:

$_engrave_text_option = isset($_POST['_engrave_text_option']) ? 'yes' : 'no'; 

所以你的meta值永远不会空值。它得到是或否。 有两种解决方案。

  1. 将“否”更改为“”;

    $ _engrave_text_option = isset($ _POST ['_ engrave_text_option'])? '是':'';

  2. 更改空== '是'

    如果(is_product()& & $ engrave_option == '是'){

+0

我不understant你在这个评论是什么意思。我的答案是否解决了这个问题中的问题?我想是的。 –

+0

谢谢。您解决复选框问题。 :-) – Craig

相关问题