Updating Woo commerce checkout Page with Additional Form Data - php

I am collecting an additional User Meta Data for my Woo commerce check out page.
woocommerce_form_field('myName', array(
'type' =>'text',
'class'=>array('my-field-class form-row-wide'),
'label'=>__('First Name'),
'placeholder'=>__('Please enter your name'),
), $checkout->get_value('myName'));
And I am updating to the database with this code:
/*Update the info with the checkout*/
add_action('woocommerce_checkout_field_update_order_meta','my_custom_checkout_field_update_meta');
function my_custom_checkout_field_update_meta($order_id){
if($_POST['MyName'])
update_post_meta($order_id, 'First Name',esc_attr($POST['MyName']));
}
Each time I submit, I get an internal server Error, even though I am working on a local machine. I need to collect that data and persist it into the order Database. Anybody help?

Update: Normally the postmeta meta_key should not use white spaces and capitals…
Also your additional field should need to be inside the checkout form, if not nothing will be submitted and nothing can be saved.
To display an custom text field and save it in the database once submitted, the best way is to use the following:
// Add checkout custom text field
add_action( 'woocommerce_before_order_notes', 'add_checkout_custom_field', 20, 1 );
function add_checkout_custom_field( $checkout) {
// Text field
woocommerce_form_field('my_name', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('First Name'),
'placeholder' =>__('Please enter your name'),
), $checkout->get_value('my_name') );
}
// Save the data to the order
add_action('woocommerce_checkout_create_order','my_custom_checkout_field_update_meta');
function my_custom_checkout_field_update_meta( $order ){
if( isset($_POST['my_name']) && ! empty($_POST['my_name']) )
$order->update_meta_data( '_my_name', sanitize_text_field($POST['my_name']) );
}
Code goes in function.php file of your active child theme (or active theme). Tested and works…
To get this data once saved in the order, use get_post_meta( $order_id, '_my_name', true ); where $order_id is the dynamic order ID…
Your additional text field will be located just before "Order notes" field:
Now your additional field is confusing as Billing and Shipping first name fields already exist in checkout page.

Related

PHP Form that returns an error if the selected date is outside a specific range - Using wordpress functions.php within a woocommerce store

Background - New to coding (loving it but slightly overwhelmed at times)
The title pretty much says it all, I am trying to add a checkout function where the customer must select a date at least two weeks after the current date. I was able to find resources to modify the cart page and how to add fields, but my lack of php knowledge has prevented me from improving the overall functionality and behaving the way I'd like it to.
Below is the code I added to the child theme. Thank you so so much in advance for the help!!!
/**
* Add Pickup Date to the checkout
*/
add_action( 'woocommerce_before_order_notes', 'my_custom_checkout_pickup_date' );
function my_custom_checkout_pickup_date( $checkout ) {
echo '<br>';
echo '<div id="my_custom_checkout_pickup_date"><h3>' . __('Pickup Date') . '</h3>';
woocommerce_form_field( 'pickup_date', array(
'type' => 'date',
'class' => array('my-field-class form-row-wide'),
'label' => __('Select a date on or after 12/22/2020'),
'required' => true,
), $checkout->get_value( 'pickup_date' ));
echo '</div>';
echo '<br>';
}
/**
* Error Message for Pickup Date
*/
add_action('woocommerce_checkout_process', 'my_custom_checkout_pickup_date_process');
function my_custom_checkout_pickup_date_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['pickup_date'] )
wc_add_notice( __( 'Please enter a pickup date for this order.' ), 'error' );
}
You can specify "min" and "max" values as custom attributes.
Please see this answer of how to specify custom attributes.
Do calculate the dates relative to "today" you can use strtotime and mktime , see this question's answers to get a hold on this.

Get custom Fields from registration to Woocommerce Checkout

Hi i am using a plugin to allow employers to register and post jobs. In the registration I have created custom fields they are also in the admin and in the Profile (VAT IDs they I need for billing). I can automaticaly fill and save them also update in the Profile or admin back-end. But I have to include them in the billing fields (not so important where maybe after company name) where they are generated into the invoice. I am not a programmer I only know html and css little bit. I am trying now for 12 hours and no chance to get it there.
I would also like to make them not-editable from user profile.
This are my fields saved in the child-theme functions.php I have done this with the help from Plugin author but he will not help me more because of no support. Plugin guide
add_action('iwj_employer_form_after_general',function ($job){
$post_id = $job ? $job->get_id() : '';
?>
<?php
iwj_field_text( '_ico_company', 'IČO spoločnosti*', true, $post_id, null, 'true', '', __( '' ) );
?>
<?php
});
add_action('iwj_admin_employer_form_after_general',function ($post_id){
?>
<?php
iwj_field_text( '_ico_company', 'IČO spoločnosti*', true, $post_id, null, 'true', '', __( '' ) );
?>
<?php
});
add_action('save_post', function($post_id){
if($post_id && get_post_type($post_id) == 'iwj_employer'){
$custom_field_value = sanitize_text_field($_POST['_ico_company']);
update_post_meta($post_id, '_ico_company', $custom_field_value);
}
}, 99);
add_action('iwj_register_process', function($uid){
$user = IWJ_User::get_user($uid);
$post_id = 0;
if($user->is_employer()){
$emp = $user->get_employer();
$post_id = $emp->get_id();
}
if($post_id){
//Add you custom field name process here
update_post_meta($post_id, '_ico_company', sanitize_text_field($_POST['_ico_company']));
}
});
I would be mega happy if someone could help me out with this :)
This will help you to have the fields in the checkout. I added a mock function get_vat_field, because I don't know yet how you are going to get the VAT field in the checkout.
Generally, it adds an additional field to the checkout, and when the checkout is completed, it adds it to the order. Which then is displayed in the order meta of the order. You can find that in the order itself in the admin panel (order edit page).
Simply add this to your functions.php of your child theme.
// Our hooked in function – $fields is passed via the filter!
function add_vat_to_checkout_fields( $fields ) {
$fields['billing']['vat'] = array(
'type' => 'text',
'label' => __('VAT', 'woocommerce'),
'placeholder' => _x('VAT', 'placeholder', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide hidden'),
'clear' => true,
'value' => get_vat_field('') // this is the function that gets the field from the user account or job post.
);
return $fields;
}
/**
* Display field value on the order edit page
*/
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta($order){
echo '<p><strong>'.__('VAT').':</strong> ' . get_post_meta( $order->get_id(), 'vat', true ) . '</p>';
}

How can I create a Custom Text Box on a WooCommerce Product Page?

I am working on a WordPress website, with WooCommerce functionality.
I have created 2 Custom Fields, for the Product Data box within the backend of the Product Page, using the following Code:
<?php
function theme_name_woocommerce_custom_fields() {
// Price Per Character
woocommerce_wp_text_input(
array(
'id' => '_character_price',
'label' => 'Price Per Character',
'description' => 'This is the amount a customer pays per letter entered.',
'desc_tip' => 'true',
'placeholder' => 'Enter Amount per Letter (Exclude the £)'
)
);
// Custom Text Box
woocommerce_wp_checkbox(
array(
'id' => '_custom_text_box',
'label' => 'Show Custom Text Box',
'description' => 'Select this box, if you would like a Custom Text Box to appear on the Product's page.',
'desc_tip' => 'true',
)
);
}
add_action( 'woocommerce_product_options_general_product_data', 'theme_name_woocommerce_custom_fields' );
function save_theme_name_woocommerce_custom_field( $post_id ) {
if ( ! empty( $_POST['_custom_text_field'] ) ) {
update_post_meta( $post_id, '_custom_text_field', esc_attr( $_POST['_custom_text_field'] ) );
}
}
add_action( 'woocommerce_process_product_meta', 'save_theme_name_woocommerce_custom_fields' );
?>
In reference to the woocommerce_wp_checkbox, I would like to create a function whereby when this checkbox is selected, it creates a Custom Text Box on the associated Product's page. This Custom Text Box can then be used by a potential customer to enter a piece of text, which they would like to have printed to the page's Product.
Is anyone aware of what additional piece of coding I would need to enter, in order to achieve said goal?
You can override simple/variable product's template file and add custom field there. Keep logic of show/hide textbox when checkbox is checked there only.
When add to cart is done, you will get all posted data in POST. Grab it from there and put into woocommerce' object.
=======================================================
Edited:
You can follow this steps:
Copy woocommerce/templates/single-product/add-to-cart/variable.php this template to your child theme and customize it. You will see a form tag there. In that you can put your custom created checkbox(which you added from admin). Also, add a custom textbox(in which user will enter text) - and hide it.
Add custom js from functions.php. - In this js you can write logic that if checkbox is checked then you will show the textbox, else not.
Now, when user does add to cart, add this custom textbox data to woocommerce object. How to enter custom data to woocommerce object - you can have step by step details here: https://wisdmlabs.com/blog/add-custom-data-woocommerce-order/

Translate custom labels fields in function.php file of my theme

With the help from the community, I have succeeded to create, save and print the labels and their values to the single product page.
I can also translate the input values into different languages using Polylang, but translating the custom labels (Conditions and Brands) is extremely hard.
Anyone out there can help me with these issues?
I tried to use Polylang, Saywhat...with no success!
Here is the code:
// Enabling and Displaying Fields in backend
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
woocommerce_wp_text_input( array( // Text Field type
'id' => '_conditions',
'label' => __( 'Conditions', 'woocommerce' ),
'placeholder' => 'i.e: brand-new; refurbished; defected...',
'desc_tip' => 'true',
'description' => __( 'Enter the conditions of the products here.', 'woocommerce' )
) );
woocommerce_wp_text_input( array( // Text Field type
'id' => '_brands',
'label' => __( 'Brands', 'woocommerce' ),
'placeholder' => 'i.e: Lacoste; Hugo Boss...etc',
'desc_tip' => 'true',
'description' => __( 'Enter names of the Brands of the products if any.', 'woocommerce' )
));
echo '</div>'; // Closing </div> tag HERE
}
// Save Fields values to database when submitted (Backend)
add_action( 'woocommerce_process_product_meta', 'woo_save_custom_general_fields' );
function woo_save_custom_general_fields( $post_id ){
// Saving "Conditions" field key/value
$conditions_field = $_POST['_conditions'];
if( !empty( $conditions_field ) )
update_post_meta( $post_id, '_conditions', esc_attr( $conditions_field ) );
// Saving "Brands" field key/value
$brands_field = $_POST['_brands'];
if( !empty( $brands_field ) )
update_post_meta( $post_id, '_brands', esc_attr( $brands_field ) );
}
add_action('woocommerce_single_product_summary', 'woo_display_custom_general_fields_values', 20);
function woo_display_custom_general_fields_values() {
global $product;
echo '<p class="custom-conditions">Conditions: ' . get_post_meta( $product->id, '_conditions', true ) . '</p>';
echo '<p class="custom-brands">Brands: ' . get_post_meta( $product->id, '_brands', true ) . '</p>';
}
And here a screenshot:
Thank you.
First, you should change the gettex domain name from 'woocommerce' to the domain name of your theme (or something more custom), as it doesn't make part of woocommerce code, and it's located in your active theme.
1) the Free alternative:
Then as it's not really content that you are trying to translate, but some peaces of code located in the function.php file of your active child theme (or active theme), you should use a specialized free plugin as Loco Translate that will provides in-browser editing of WordPress translation files.
Loco Translate, also provides localization tools for developers, such as extracting strings and generating templates.
Loco Translate features include:
Built-in translation editor within WordPress admin
Create and update language files directly in your theme or plugin
Extraction of translatable strings from your source code
Native MO file compilation without the need for Gettext on your system
Support for PO features including comments, references and plural forms
PO source view with clickable source code references
Protected language directory for saving custom translations
Configurable PO file backups
Built-in WordPress locale codes
2) The commercial complete way (completely compatible with WooCommerce):
The most complete commercial alternative is WPML plugin, that will also handle perfectly and more easily WooCommerce custom localisation and translations content for multilingual web sites. The other free optional plugins are incomplete for WooCommerce and much more difficult to get them work totally well.
So If you are planing to publish a multilingual website, think about it.

Change town/city text field to Select Option field in checkout form

In Woocommerce, I would like to change Town/City text field in a select field option field.
What should i do?
Here is a screenshot:
Thanks
You need first to change the field type from 'text' to 'select' using the dedicated hook woocommerce_default_address_fields. Then you have also to change the label and to and an options argument where you are going to set your towns in an array of key/values.
In this array, you will have a line by town separated by a coma.
Here is the code:
add_filter( 'woocommerce_default_address_fields' , 'customize_checkout_city_field' );
function customize_checkout_city_field( $address_fields ) {
// Set HERE the cities (one line by city)
$towns_cities_arr = array(
'0' => __('Select your city', 'my_theme_slug'),
'paris' => 'Paris',
'versailles' => 'Versailles',
'cannes' => 'Cannes',
);
// Customizing 'billing_city' field
$address_fields['city']['type'] = 'select';
$address_fields['city']['class'] = array('form-row-last', 'my-custom-class'); // your class here
$address_fields['city']['label'] = __('Town / city', 'my_theme_slug');
$address_fields['city']['options'] = $towns_cities_arr;
// Returning Checkout customized fields
return $address_fields;
}
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
The code is tested and fully functional.
Update: To add your custom class, replace in $address_fields['city']['class']… the class 'my-custom-class' by yours.
References:
Customizing checkout fields using actions and filters - Overriding core fields
You can customize the checkout fields by actions and filters.
Please refer the official documentation here
// Add these code in your theme's function.php
add_filter( 'woocommerce_default_address_fields' , 'custom_override_default_address_fields' );
// Our hooked in function - $address_fields is passed via the filter!
function custom_override_default_address_fields( $fields) {
$fields['billing']['your_field']['options'] = array(
'option_1' => 'Option 1 text',
'option_2' => 'Option 2 text'
);
return $fields;
}
In case you are looking for a plugin you can use checkout field editor from woocommerce team.

Categories