2017-11-25 171 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

相關問題