Alessandro Baio
Alessandro Baio

Reputation: 11

Display an existing value on conditional custom checkout fields in Woocommerce

In Woocommerce I'm using the code from this answer thread:

WooCommerce conditional custom checkout fields

It works fine, but the problem is that it doesn't display the "Codice fiscale" value checkout, when "Codice fiscale" value exists since a previous order (or from user data).

Any help is appreciated?

Upvotes: 1

Views: 941

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

I have revisited this old answer and making some changes in the code.

Now on checkout page, if the "codice fiscale" exist, the checkbox will be hidden and the "codice fiscale" value will appear in it's field.

The new code:

add_filter( 'woocommerce_checkout_fields' , 'cbi_codice_fiscale_checkout_fields' );
function cbi_codice_fiscale_checkout_fields ( $fields ) {
    // if ( ICL_LANGUAGE_CODE !='it' ) return $fields; // Only for Italy

    $domain = 'cbi-custom-parts';

    $fields['billing']['checkbox_cf'] = array(
        'type'      => 'checkbox',
        'label'     => __('Voui la fattura? (solo per privati)', $domain),
        'class'     => array('form-row-wide'),
        'clear'     => true,
     );

    $codice_fiscale = get_user_meta( get_current_user_id(), 'billing_codice_fiscale', true );

    $label_cf = $codice_fiscale ? __('Codice fiscale', $domain) : __('Inserisci il codice fiscale', $domain);
    $required = $codice_fiscale ? true : false;

    $fields['billing']['billing_codice_fiscale'] = array(
        'label'     => $label_cf,
        'placeholder'   => _x('RSSMRA85T10A562S', 'placeholder', $domain),
        'class'     => array('form-row-wide'),
        'clear'     => true,
        'required'  => $required,
     );

    return $fields;
}

add_action( 'woocommerce_after_checkout_form', 'cbi_cf_conditionally_hide_show', 6);
function cbi_cf_conditionally_hide_show() {
    // if ( ICL_LANGUAGE_CODE !='it' ) return; // Only for Italy
    $required = esc_attr__( 'required', 'woocommerce' );

    $user_codice_fiscale = get_user_meta( get_current_user_id(), 'billing_codice_fiscale', true );
    ?>
    <script type="text/javascript">
        (function($){
            var required = '<abbr class="required" title="<?php echo $required; ?>">*</abbr>', // Required html
                bcf = '#billing_codice_fiscale', bcff = bcf+'_field',
                vr  = 'validate-required';

            // If codice fiscale exist we hide the checkbox
            <?php if( $user_codice_fiscale): ?>
            $('#checkbox_cf_field').hide();

            // If codice fiscale doesn't exist we hide the "codice fiscale" field and enable the script
            <?php else: ?>

            $(bcff+' > '+bcf).prop('pattern', "^[a-zA-Z]{6}[0-9]{2}[a-zA-Z][0-9]{2}[a-zA-Z][0-9]{3}[a-zA-Z]$"); // Doesn't seem to do something
            $(bcff).hide();

            $('input#checkbox_cf').change(function(){
                if (this.checked) {
                    $(bcff).fadeIn("fast", function(){
                        $(this).addClass(vr);
                        $(bcff+' > label').append(required);
                    });
                } else {
                    $(bcff).fadeOut("fast", function(){
                        $(this).removeClass(vr);
                        $(bcff+' > label > .required').remove();
                    });
                }
                $(bcff).val('');
                $(bcff).removeClass("woocommerce-validated");
                $(bcff).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
            });
            <?php endif; ?>
        })(jQuery);
    </script>
    <?php
}

// Utility function checking "codice fiscale" validity
function is_cf_valid( $valore, $codice_fiscale = true ){
    $espressione = "^[a-z]{6}[0-9]{2}[a-z][0-9]{2}[a-z][0-9]{3}[a-z]$";
    if( ! $codice_fiscale ) $espressione = "^[0-9]{11}$";
    return eregi( $espressione, $valore ) ? true : false;
}

// Check custom fields value "codice fiscale" when submit and return error notices (if needed)
add_action('woocommerce_checkout_process', 'cbi_cf_process');
function cbi_cf_process() {
    if ( isset($_POST['checkbox_cf']) && $_POST['checkbox_cf'] == 1 ) {
        if( empty( $_POST['billing_codice_fiscale'] ) ) {
            wc_add_notice( __( "Please don't forget to enter your Codice Fiscale/Partita Iva", "cbi-custom-parts" ), "error" );
        } else {
            $valid_codice_fiscale = is_cf_valid( $_POST['billing_codice_fiscale'] );
            if( ( ! $valid_codice_fiscale ) )
                wc_add_notice( __( "Wrong data in Codice Fiscale/Partita Iva field", "cbi-custom-parts" ), "error" );
        }
    } else if( isset( $_POST['billing_codice_fiscale'] ) && ! empty( $_POST['billing_codice_fiscale'] ) ) {
        $valid_codice_fiscale = is_cf_valid( $_POST['billing_codice_fiscale'] );
        if( ( ! $valid_codice_fiscale ) )
            wc_add_notice( __( "Wrong data in Codice Fiscale/Partita Iva field", "cbi-custom-parts" ), "error" );
    }
}

// Save the custom field value "codice fiscale" in order meta and in user meta
add_action( 'woocommerce_checkout_update_order_meta', 'cbi_codice_fiscale_update_order_meta' );
function cbi_codice_fiscale_update_order_meta ( $order_id ) {
    if ( empty( $_POST['billing_codice_fiscale'] ) ) return;

    $customer_id = get_post_meta( $order_id, '_customer_user', true );

    update_user_meta( $customer_id, 'billing_codice_fiscale', sanitize_text_field( $_POST['billing_codice_fiscale'] ) );
    update_post_meta( $order_id, '_billing_codice_fiscale', sanitize_text_field( $_POST['billing_codice_fiscale'] ) );
}

// Backend : Display in Order edit pages, after billing address, the custom field value "codice fiscale"
add_action( 'woocommerce_admin_order_data_after_billing_address', 'cbi_cf_admin_order_data_after_billing_address', 10, 1 );
function cbi_cf_admin_order_data_after_billing_address( $order ){
    $codice_fiscale = get_post_meta( $order->get_id(), '_billing_codice_fiscale', true );
    if( ! empty( $codice_fiscale ) )
        echo '<p><strong>'.__('Codice Fiscale', 'cbi-cf-invoice').':</strong> ' . $codice_fiscale . '</p>';
}

// Backend: Display and edit user profile custom field value "codice fiscale" Only for Italy
add_action( 'show_user_profile', 'add_extra_user_codice_fiscale', 1, 1 );
add_action( 'edit_user_profile', 'add_extra_user_codice_fiscale', 1, 1 );
function add_extra_user_codice_fiscale( $user )
{

    //if( get_user_meta( $user->ID, 'billing_country', true ) != 'IT' ) return;  // Only for Italy
    $codice_fiscale = get_user_meta( $user->ID, 'billing_codice_fiscale', true );
    if( empty( $codice_fiscale ) ) $codice_fiscale = '';
    ?>
        <h3><?php _e( "Codice fiscale", "cbi-custom-parts" ); ?></h3>
        <table class="form-table"><tr>
            <th><label for="billing_codice_fiscale"><?php _e( "Codice fiscale", "cbi-custom-parts" ); ?></label></th>
            <td><input type="text" name="billing_codice_fiscale" value="<?php echo esc_attr($codice_fiscale); ?>" class="regular-text" /></td>
        </tr></table><br />
    <?php
}

// Backend: Save edited user profile custom field value "codice fiscale" Only for Italy
add_action( 'personal_options_update', 'save_extra_user_codice_fiscale' );
add_action( 'edit_user_profile_update', 'save_extra_user_codice_fiscale' );
function save_extra_user_codice_fiscale( $user_id )
{
    if( ! empty( $_POST['billing_codice_fiscale'] ) )
        update_user_meta( $user_id, 'billing_codice_fiscale', sanitize_text_field( $_POST['billing_codice_fiscale'] ) );
}

Code goes in function.php file of your active child theme (or active theme). Tested and work.

Upvotes: 1

Related Questions