這個程式碼段可能會很有用,有幾個原因。當您需要對結帳及其領域進行高階定製時,希望您再感謝我🙂
在今天的片段中,我們將新增一個新的覈取方塊和另一個新的 「隱藏」 欄位 – 然後,如果勾選該覈取方塊,該欄位將顯示,否則將再次消失。

PHP 片段:新增覈取方塊以隱藏/顯示結帳欄位
/** * @snippet Add a Checkbox to Hide/Show Checkout Field - WooCommerce * @sourcecode https://businessbloomer.com/?p=21948 * @author Rodolfo Melogli * @compatible WC 2.6.14, WP 4.7.2, PHP 5.5.9 */ add_filter( 'woocommerce_checkout_fields' , 'bbloomer_display_checkbox_and_new_checkout_field' ); function bbloomer_display_checkbox_and_new_checkout_field( $fields ) { $fields['billing']['checkbox_trigger'] = array( 'type' => 'checkbox', 'label' => __('Checkbox label', 'woocommerce'), 'class' => array('form-row-wide'), 'clear' => true ); $fields['billing']['new_billing_field'] = array( 'label' => __('New Billing Field Label', 'woocommerce'), 'placeholder' => _x('New Billing Field Placeholder', 'placeholder', 'woocommerce'), 'class' => array('form-row-wide'), 'clear' => true ); return $fields; } add_action( 'woocommerce_after_checkout_form', 'bbloomer_conditionally_hide_show_new_field', 6); function bbloomer_conditionally_hide_show_new_field() { ?> <script type="text/javascript"> jQuery('input#checkbox_trigger').change(function(){ if (this.checked) { jQuery('#new_billing_field_field').fadeOut(); jQuery('#new_billing_field_field input').val(''); } else { jQuery('#new_billing_field_field').fadeIn(); } }); </script> <?php }
如何新增此程式碼?
1 、您可以將 PHP 程式碼片段放置在主題或子主題的 functions.php 檔案的底部 (如果是 CSS 程式碼,請新增到子主題的 style.css 檔案底部) 修改之前建議先備份原始檔案,若出現錯誤請先刪除此程式碼。
2 、 WordPress 4.9 後改進了主題編輯器,對於 CSS 程式碼也可開啟網站前臺編輯器的 【自定義】,複製程式碼新增到自定義 css 中。
此程式碼是否可用?
如需幫助或是您有更好的方案想分享?請到薇曉朵 WooCommerce 中文論壇留言告知,我們希望可以幫到更多國內的 WooCommerce 使用者也希望您的參與。