Удалить текст "(необязательно)" из полей условного оформления заказа в Woocommerce 3.4


Ранее я использовал этот ответ , чтобы скрыть поля оформления заказа на основе выбранного способа доставки, он работал нормально до обновления (текущая версия 3.4.2), я думаю, не уверен, что изменилось, но он больше не работает так, как предполагалось.

Ранее, когда была выбрана локальная доставка, некоторые поля были скрыты и сделаны необязательными, а когда была выбрана доставка, эти поля снова отображались динамически без перезагрузки страницы.

Теперь он показывает и скрывает поля по мере необходимости, однако, когда выбрана доставка, отображаются правильные поля, помеченные как обязательные, но рядом с ними также есть знак (необязательно), и это делает его необязательным. См. Рисунок ниже.

enter image description here

Вот мой модифицированный кусачий нож ниже:

add_filter('woocommerce_default_address_fields', 'custom_default_checkout_fields', 10, 1 );
function custom_default_checkout_fields( $address_fields ) {
$custom_fields = array( 'country', 'address_1', 'address_2', 'state', 'postcode');
foreach($custom_fields as $field)
    $address_fields[$field]['required'] = false;
return $address_fields;
}

add_action( 'wp_footer', 'custom_checkout_field_script' );
function custom_checkout_field_script() {

$pickpoint = 'local_pickup:2';
$free_delivery = 'free_shipping:1';
$flat_rate = 'flat_rate:3';

$required = esc_attr__( 'required', 'woocommerce' );
?>
<script>
    jQuery(function($){

        var shippingMethod = $('input[name^="shipping_method"]:checked'),
            required = '<abbr class="required" title="<?php echo $required; ?>">*</abbr>',
            shippingChecked = $('input#ship-to-different-address-checkbox');

        shippingChecked.change( function(){
            console.log('Shipping Checked: '+shippingChecked.prop('checked'));
        });

        function showHide( actionToDo='show', selector='' ){
            if( actionToDo == 'show' )
                $(selector).show(function(){
                    $(this).addClass("validate-required");
                    $(this).removeClass("woocommerce-validated");
                    $(this).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
                    if( $(selector+' > label > abbr').html() == undefined )
                        $(selector+' label').append(required);
                });
            else
                $(selector).hide(function(){
                    $(this).removeClass("validate-required");
                    $(this).removeClass("woocommerce-validated");
                    $(this).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
                    if( $(selector+' > label > abbr').html() != undefined )
                        $(selector+' label > .required').remove();
                });
        }

        if( shippingMethod.val() == '<?php echo $pickpoint; ?>' )
        {
            showHide('show','#billing_country_field' );
            showHide('hide','#billing_address_1_field' );
            showHide('hide','#billing_address_2_field' );
            showHide('hide','#billing_postcode_field' );
            showHide('hide','#billing_state_field' );
        }
        else if( shippingMethod.val() == '<?php echo $free_delivery; ?>' || '<?php echo $flat_rate; ?>')
        {
            showHide('show','#billing_address_1_field');
            showHide('show','#billing_address_2_field');
            showHide('show','#billing_postcode_field');
            showHide('hide','#billing_state_field');
            showHide('hide','#billing_country_field');
        }

        $( 'form.checkout' ).on( 'change', 'input[name^="shipping_method"]', function() {
            var shipMethod = $('input[name^="shipping_method"]:checked');
            if( shipMethod.val() == '<?php echo $pickpoint; ?>' )
            {
                showHide('show','#billing_country_field');
                showHide('hide','#billing_address_1_field');
                showHide('hide','#billing_address_2_field');
                showHide('hide','#billing_postcode_field');
                showHide('hide','#billing_state_field');
            }
            else if( shipMethod.val() == '<?php echo $free_delivery; ?>' || '<?php echo $flat_rate; ?>')
            {
                showHide('show','#billing_address_1_field');
                showHide('show','#billing_address_2_field');
               showHide('show','#billing_postcode_field');
                showHide('hide','#billing_state_field');
                showHide('hide','#billing_country_field');
            }
            else
            {
                showHide('show','#billing_address_1_field');
                showHide('show','#billing_address_2_field');
                showHide('show','#billing_postcode_field');
                showHide('show','#billing_state_field');
                showHide('show','#billing_country_field');
            }
        });

        $( 'input#ship-to-different-address-checkbox' ).click( function() {
            var shipMethod = $('input[name^="shipping_method"]:checked');
            if( shipMethod.val() == '<?php echo $pickpoint; ?>' && shippingChecked.prop('checked') == true )
            {
                showHide('show','#billing_country_field');
                showHide('hide','#billing_address_1_field');
                showHide('hide','#billing_address_2_field');
                showHide('hide','#billing_postcode_field');
                showHide('hide','#billing_state_field');

                showHide('show','#shipping_country_field');
                showHide('hide','#shipping_address_1_field');
                showHide('hide','#shipping_address_2_field');
                showHide('hide','#shipping_postcode_field');
                showHide('hide','#shipping_state_field');
            }
            else if( shipMethod.val() == '<?php echo $free_delivery; ?>' || '<?php echo $flat_rate; ?>' && shippingChecked.prop('checked') == true )
            {
                showHide('show','#billing_address_1_field');
                showHide('show','#billing_address_2_field');
                showHide('show','#billing_postcode_field');
                showHide('hide','#billing_state_field');
                showHide('hide','#billing_country_field');

                showHide('show','#shipping_address_1_field');
                showHide('show','#shipping_address_2_field');
                showHide('show','#shipping_postcode_field');
                showHide('hide','#shipping_state_field');
                showHide('hide','#shipping_country_field');
            }
            else if( shippingChecked.prop('checked') == false )
            {
                showHide('show','#shipping_address_1_field');
                showHide('show','#shipping_address_2_field');
                showHide('hide','#shipping_state_field');
                showHide('hide','#shipping_country_field');
            }
        });
    });
</script>
<?php
}

Любые указатели будут весьма признательны!

Author: LoicTheAztec, 2018-06-09

1 answers

Обновление 2

Чтобы удалить "(необязательно)" текст из меток полей оформления заказа, введенных в версии 3.4 Woocommerce, как и раньше, вам нужно будет добавить следующий код:

// PHP: Remove "(optional)" from our non required fields
add_filter( 'woocommerce_form_field' , 'remove_checkout_optional_fields_label', 10, 4 );
function remove_checkout_optional_fields_label( $field, $key, $args, $value ) {
    // Only on checkout page
    if( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return $field;

    $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
    $keys = array( 'billing_country', 'billing_address_1', 'billing_state', 'billing_postcode',
                'shipping_country', 'shipping_address_1', 'shipping_state', 'shipping_postcode' );

    if( in_array($key, $keys) )
        return str_replace( $optional, '', $field );
    else
        return $field;
}

// JQuery: Needed for checkout fields to Remove "(optional)" from our non required fields
add_filter( 'wp_footer' , 'remove_checkout_optional_fields_label_script' );
function remove_checkout_optional_fields_label_script() {
    // Only on checkout page
    if( ! ( is_checkout() && ! is_wc_endpoint_url() ) ) return;

    $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
    ?>
    <script>
    jQuery(function($){
        // On "update" checkout form event
        $(document.body).on('update_checkout', function(){
            $('#billing_country_field label > .optional').remove();
            $('#billing_address_1_field label > .optional').remove();
            $('#billing_postcode_field label > .optional').remove();
            $('#billing_state_field label > .optional').remove();
            $('#shipping_country_field label > .optional').remove();
            $('#shipping_address_1_field label > .optional').remove();
            $('#shipping_postcode_field label > .optional').remove();
            $('#shipping_state_field label > .optional').remove();
        });
    });
    </script>
    <?php
}

Вводится код function.php файл вашей активной дочерней темы (или активной темы). Протестирован и работает в Woocommerce версии 3.4+.

Вы можете объединить включенный код jQuery с существующим кодом jQuery...

 3
Author: LoicTheAztec, 2018-06-10 22:38:40