logo
down
shadow

Translate checkout fields validation error notices in Woocommerce


Translate checkout fields validation error notices in Woocommerce

By : zhenghao.long
Date : November 21 2020, 04:01 AM
I wish this helpful for you 1) Customizing default validation error notices for Woocommerce checkout fields:
You can use woocommerce_checkout_required_field_notice dedicated filter hook, to customize each notice, changing the text below:
code :
add_filter( 'woocommerce_checkout_required_field_notice', 'custom_checkout_required_fields_error_notice', 10, 2 );
function custom_checkout_required_fields_error_notice( $error_notice, $field_label ) {
    $error_notice = sprintf( __( '%s is a required field.', 'woocommerce' ), '<strong>' . esc_html( $field_label ) . '</strong>' );

    return $error_notice; 
}


Share : facebook icon twitter icon
qTranslate + WooCommerce-qTML + WooCommerce Aggiungere CF e P.IVA not translate custom fields in checkout page

qTranslate + WooCommerce-qTML + WooCommerce Aggiungere CF e P.IVA not translate custom fields in checkout page


By : Yogi
Date : March 29 2020, 07:55 AM
will be helpful for those in need Ok I resolved it. Post here the solution for someone that has my same problem.
code :
    load_plugin_textdomain('your_plugin_identifier', false, dirname( plugin_basename(__FILE__) ) . '/languages');

add_action('init', 'init_textdomain');
function init_textdomain() {
   load_plugin_textdomain(''your_plugin_identifier', false, dirname( plugin_basename(__FILE__) ) . '/languages');
}
WooCommerce: update custom fields after checkout validation failure

WooCommerce: update custom fields after checkout validation failure


By : Torgeir Hansen
Date : March 29 2020, 07:55 AM
To fix this issue The code provided was mostly un-useful… I have make a lot of changes and optimizations. All my code is commented, it's tested on WooCommerce 3+ and perfectly works.
code :
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field' );

function my_custom_checkout_field( $checkout ) {

    // The 2 Options arrays in imput select
    $delivery_time_list[''] = $takeaway_time_list[''] = __('Select an hour');
    for($h = 10, $i = 0; $i < 8; $i++  ){
        if( $i % 2 == 0 ){
            $time = $h.':00';
            $delivery_time_list[$time] = 'deliver '.$time;
        } else {
            $time = $h.':30';
            $h++;
        }
        $takeaway_time_list[$time] = 'takeaway '.$time;
    }

    echo '<div id="delivery_checkout_fields"><h3>' . __('Shipping time options') . '</h3>';

    woocommerce_form_field( 'delivery_time', array(
        'type'      => 'select',
        'class'     => array('delivery-time form-row-wide'),
        'label'     => __('Delivery time'),
        'options'   => $delivery_time_list,
    ), $checkout->get_value( 'delivery_time' ) );

    woocommerce_form_field( 'takeaway_time', array(
        'type'      => 'select',
        'class'     => array('takeaway-time form-row-wide'),
        'label'     => __('Take away time'),
        'options'   => $takeaway_time_list,
    ), $checkout->get_value( 'takeaway_time' ) );

    echo '</div>';

    $required = esc_attr__( 'required', 'woocommerce' );

    ?>
    <script>
        jQuery(function($){

            var choosenShipMethod = $('input[name^="shipping_method"]:checked').val().split(':')[0], // Choosen shipping method slug
                required = '<abbr class="required" title="<?php echo $required; ?>">*</abbr>'; // Required html

            // TESTING: displaying in console the choosen shipping
            console.log('Chosen shipping: '+choosenShipMethod);

            // Function that shows or hide imput select fields
            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");
                        $(selector+' label').append(required);
                        //console.log('Selector (show): '+selector);
                    });
                else
                    $(selector).hide(function(){
                        $(this).removeClass("validate-required");
                        $(this).removeClass("woocommerce-validated");
                        $(this).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
                        $(selector+' label > .required').remove();
                        //console.log('Selector (hide): '+selector);
                    });
            }

            // Initialising at start (Based on the choosen shipping method)
            if( choosenShipMethod == 'flat_rate' ) // Choosen "Delivery" (Hidding "Take away")
            {
                showHide('show','#delivery_time_field' );
                showHide('hide','#takeaway_time_field' );
            }
            else if( choosenShipMethod == 'local_pickup' ) // Choosen "Take away" (Hidding "Delivery")
            {
                showHide('show','#takeaway_time_field' );
                showHide('hide','#delivery_time_field' );
            }
            else // No shipping choosen yet (Hidding BOTH shipping dropdown hour selectors
            {
                showHide('hide','#delivery_time_field' );
                showHide('hide','#takeaway_time_field' );
                $('#delivery_checkout_fields').hide();
            }

            // When shipping method is changed (Live event)
            $( 'form.checkout' ).on( 'change', 'input[name^="shipping_method"]', function() {
                var changedShipMethod = $('input[name^="shipping_method"]:checked').val().split(':')[0];
                if( changedShipMethod == 'flat_rate' )
                {
                    // Choose "Delivery" | Show "Delivery" and Hide "Take away"
                    $('#delivery_checkout_fields').show();
                    showHide('show','#delivery_time_field' );
                    showHide('hide','#takeaway_time_field' );
                }
                else if( changedShipMethod == 'local_pickup' )
                {
                    // Choose "Take away" | Show "Take away" and Hide "Delivery"
                    $('#delivery_checkout_fields').show();
                    showHide('show','#takeaway_time_field' );
                    showHide('hide','#delivery_time_field' );
                }
                console.log("Chosen shipping: "+changedShipMethod);
            });

            // When an hour is selected (LIVE event)
            $('#delivery_checkout_fields select').change( function(){
                if( $(this).val() != '')
                    $(this).parent().removeClass("validate-required");
                else
                    $(this).parent().addClass("validate-required");

                console.log("Selector value: "+$(this).val());
            });
            // "select.shipping_method, input[name^="shipping_method"], #ship-to-different-address input, .update_totals_on_change select, .update_totals_on_change input[type="radio"], .update_totals_on_change input[type="checkbox"]"
            //"function (){t.reset_update_checkout_timer(),t.dirtyInput=!1,e(document.body).trigger("update_checkout")}"
        });
    </script>
    <?php

}


// Process the checkout (Checking if required fields are not empty)
add_action('woocommerce_checkout_process', 'ba_custom_checkout_field_process');
function ba_custom_checkout_field_process() {

    $delivery_time = $takeaway_time = 0;
    if ( $_POST['delivery_time'] ) $delivery_time = 1;
    if ( $_POST['takeaway_time'] ) $takeaway_time = 1;

    // Only one message is possible for both
    if ( ( $delivery_time + $takeaway_time ) == 0 ){
        wc_add_notice( __('Please select a <strong>shipping time</strong>.' ), 'error');
    }
}


## CALCULATING THE DELIVERY FEE (BASED ON COUNTING THE DIFFERENT DATES For all items) ##
add_filter( 'woocommerce_package_rates', 'custom_shipping_flat_rate_cost_calculation', 10, 2 );
function custom_shipping_flat_rate_cost_calculation( $rates, $package )
{
    ## --- CALCULATIONS Based on CART DATA (if needed) --- ##

    foreach(WC()->cart->get_cart() as $cart_item ):
        // HERE your incredibly complex code used to calculate delivery costs
    endforeach;


    ## --- CHANGING DYNAMICALLY THE METHODS COSTS --- ##

    foreach($rates as $rate_key => $rate_values):

        $method_id = $rate_values->method_id;
        $rate_id = $rate_values->id;

        // "DELIVERY" - "local_pickup" method (if needed)
        if ( 'flat_rate' === $method_id ){

            // HERE your incredibly complex code used to calculate delivery costs

            // Change the price cost
            $price_excl_tax = $rates[$rate_id]->cost + 2.5;
            $rates[$rate_id]->cost =  number_format($price_excl_tax, 2);

            $tax_calculation = $rates[$rate_id]->taxes[0] * 0.1;
            $rates[$rate_id]->taxes[0] = number_format($tax_calculation, 2);
        }
        // "TAKE WAY" - "local_pickup" method (if needed)
        elseif ( 'local_pickup' === $method_id )
        {
            // do something if needed
        }

    endforeach;

    return $rates;
}


// Save the "shipping time" in order meta data
add_action( 'woocommerce_checkout_update_order_meta', 'save_shipping_time_in_order_meta',  100, 1 );
function save_shipping_time_in_order_meta( $order_id ) {

    // Take away time
    $takeaway_time = $_POST['takeaway_time'];
    if ( ! empty( $takeaway_time ) ){
        add_post_meta( $order_id, '_shipping_time', $takeaway_time );
        add_post_meta( $order_id, '_shipping_type', __('Take away', 'woocommerce' ) );
    }
    // Delivery time
    $delivery_time = $_POST['delivery_time'];
    if ( ! empty( $delivery_time ) ){
        add_post_meta( $order_id, '_shipping_time', $delivery_time );
        add_post_meta( $order_id, '_shipping_type', __('Delivery', 'woocommerce' ) );
    }

}

// Adding shipping time metabox (on right side) to Order edit pages
add_action( 'add_meta_boxes', 'add_order_shipping_time_meta_boxe' );
function add_order_shipping_time_meta_boxe(){

    add_meta_box(
        'woocommerce-order-shipping-time-values', __( 'Shipping type and time', 'woocommerce' ),
        'order_shipping_time_values', 'shop_order', 'side', 'default'
    );
}

// Adding content to shipping time metabox to Order edit pages
function order_shipping_time_values(){
    global $post;

    $type = get_post_meta($post->ID, '_shipping_type', true);
    $time = get_post_meta($post->ID, '_shipping_time', true);

    echo "<p><strong>Type:</strong> $type | <strong>time:</strong> $time</p>";
}
Custom checkout fields validation in Woocommerce 3

Custom checkout fields validation in Woocommerce 3


By : cobe
Date : March 29 2020, 07:55 AM
it fixes the issue Updated
Note: Your code only works if you have one unique item in cart… If you have 2 different bookings items, it will handle only the last added one.
code :
// Add a new checkout field
add_filter( 'woocommerce_checkout_fields', 'ppp_filter_checkout_fields' );
function ppp_filter_checkout_fields($fields){

    $fields['extra_fields'] = array(
    'participant_details' => array(
        'type' => 'participant_details',
        'required'      => false,
        'label' => __( 'Participant Details' )
        ),
    );

    // Add a "persons" hidden input field
    foreach( WC()->cart->get_cart() as $cart_item ) {
        $persons = $cart_item['booking']['_persons'][0];
    }
    echo '<input type="hidden" name="persons" value="' . $persons . '">';

    return $fields;
}
//* Validate custom checkout fields
add_action( 'woocommerce_after_checkout_validation', 'ppp_checkout_field_participant_details_validation', 20, 2 );
function ppp_checkout_field_participant_details_validation( $data, $errors ){
    if ( isset( $_POST['persons'] ) && $_POST['persons'] > 1 ){

        for ( $i = 1, $j = 2; $i < esc_attr( $_POST['persons'] ); $i++, $j++ ) {
            if ( empty( $_POST['participant_details'][$i]['full_name'] ) )
                $errors->add( 'participant_'.$i.'_full_name',  __( "Please fill in the participant $j full name" ), 'error' );

            if ( empty( $_POST['participant_details'][$i]['email_address'] ) )
                $errors->add( 'participant_'.$i.'_email_address',  __( "Please fill in the participant $j email address" ), 'error' );
        }
    }
}
Email fields comparison validation in Woocommerce checkout

Email fields comparison validation in Woocommerce checkout


By : user2083685
Date : March 29 2020, 07:55 AM
may help you . I have merged this validation with the gift validation from this question code you have made before, so you will remove it from your actual code as this function handle both of them:
code :
add_action('woocommerce_after_checkout_validation', 'gift_custom_field_validation', 20, 2 );
function gift_custom_field_validation( $data, $errors ) {
    // Validating that "Gift" is not empty when selected
    if( isset($_POST['gift_msg']) && isset($_POST['gift']) && empty($_POST['gift']) )
        $errors->add( 'gift', __( "You've chosen to send this as a gift, but did not submit a recipient email address.", "woocommerce" ) );

    // Validating that "Gift" imputed email is different from billing email
    if ( isset($_POST['gift']) && $data['billing_email'] === $_POST['gift'] ) {
        $errors->add( 'gift', __( "To send as gift, you cannot send it to yourself. That's the point of a gift, isn't it?", "woocommerce" ) );
    }
}
Custom validation of WooCommerce checkout fields

Custom validation of WooCommerce checkout fields


By : Darina Ignatieva
Date : March 29 2020, 07:55 AM
Hope this helps I have not seen your code that hooks these up to the woocommerce checkout flow. please check their documentation on
woocommerce_checkout_process and woocommerce_checkout_order_processed
Related Posts Related Posts :
  • LibreOffice convert PDF to Word as textbox instead normal document
  • php laravel swift email sending problems
  • Reload PHP file in command line PHP-CLI
  • how do I fetch a certain part out of an database?
  • CodeIgniter URL Route with ID and title
  • Add a header to each column
  • How can I loop stdClass in PHP?
  • Four arrays in for each loop
  • bootstrap 4 cards with php foreach loop
  • Codeigniter return not found on the server
  • PHP Codeigniter Do Upload Function Does Not Work
  • Implement REST API Symfony 3
  • how to add show data button in Yajrabox
  • My WampServer doesnt have apache setting in tray icon
  • Embedding nested form type fields in empty symfony form
  • PHP Laravel orderby not working if using `count`
  • Laravel 5.7 my model from my parameter return's empty when i dump it
  • How to pass input value as array instead of passing only one value where array_walk is used in PHP?
  • Replace illegal charactes in a text by underscore in PHP
  • PHP / JSON - Return large string result in error
  • Yii2 DI container: registering same class twice, but with different constructor parameters
  • Creating Subdirectories with a for loop
  • Wordpress get most popular posts in current post category
  • Replace linebreak in specific piece of text in file
  • Update database that has same key with using a new different values
  • Problems with Curl in Discord Oauth2
  • How to remove all lines in file till a specific word occures PHP
  • How to use Join in Codeigniter for update Query
  • PHP DOMDocument: may a text node be reused?
  • How to read Armenian texts from Laravel MSSQL database
  • How to view image and pdf files preview in yii2 kartik multiple file upload in update form
  • Which one is best and faster method ?(making drop down method)
  • Using preg_match to get content between tags
  • Laravel 5.7 Eloquent
  • How to combine array inside foreach loop
  • Wordpress-Stripe Integration: Fatal error: Uncaught Error: Class 'Stripe' not found
  • Redirect user to original url from age verification
  • How to update only one input in Laravel form?
  • How to add language translation in JSON file in prestashop
  • Interface 'Monolog\ResettableInterface' not found when running a new project
  • Adding strings when using echo in foreach PHP
  • do-while loop only runs once
  • Need to trim string
  • Increment ID by one on duplicate with PHP
  • insert current date time using laravel
  • call_user_func_array("shell_exec", ...) not working in php
  • PHP Time Validator to accept 1 digit number for hour and minutes
  • How to swap element according to condition in PHP where there is array_map?
  • PHP Compress Image and rename
  • PHP 'Delete all between' specific words
  • PHP - Show database values in text boxes
  • Merged description and additional information. Border not extending to content
  • Hide on sale products from a shortcode on homepage in Woocommerce
  • Can i use empty() for a Undefined Variable?
  • Display array from php using html form checkbox
  • Add a custom taxonomy filter after product category filter in Woocommerce Admin products list
  • CSV Import Super Slow after upgrading to PHP 7.1 only on live server
  • Order a PHP Dropdown Menu by ID as Opposed to Alphabetical Order
  • I am getting this error Error: Incorrect time value: '16:44:09 PM' for column 'time' at row 1 and I'm not sure why
  • Not Able to Load All WP-QUERY result to JSON Encode in Custom Loop
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org