Add optional additional fee to checkout - wordpress

i am using this following code to show the option to add an additional fee (product) to the cart on the "cart" page. It is working great but it is now showing on the cart page, but how do i get it to show on the checkout page additionally:
<?php
/* ADD custom theme functions here */
add_filter( 'woocommerce_price_trim_zeros', 'wc_hide_trailing_zeros', 10, 1 );
function wc_hide_trailing_zeros( $trim ) {
return true;
}
add_action('woocommerce_cart_totals_after_shipping', 'wc_shipping_insurance_note_after_cart');
function wc_shipping_insurance_note_after_cart() {
global $woocommerce;
$product_id = 971;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found ):
?>
<tr class="shipping">
<th><?php _e( 'Gift wrapper', 'woocommerce' ); ?></th>
<td><?php _e( 'Add ($3)' ); ?> </td>
</tr>
<?php else: ?>
<tr class="shipping">
<th><?php _e( 'Gift wrapper', 'woocommerce' ); ?></th>
<td>$3</td>
</tr>
<?php endif;
}
I have tried different methods, and it should be pretty basic but i am rusty on my Functions.php skills.

You could try copying the function and giving it a new name. Then change the hook depending on where you want it on the checkout page.
Here is a great visual guide to the hooks on the checkout page: https://www.businessbloomer.com/woocommerce-visual-hook-guide-checkout-page/
Try something like this:
Notice how I changed the hook from woocommerce_cart_totals_after_shipping to woocommerce_before_checkout_form here you can experiment using the hooks on the guide I linked to. I also changed the name of the function from wc_shipping_insurance_note_after_cart to wc_shipping_insurance_note_after_checkout to avoid conflicts.
add_action('woocommerce_before_checkout_form', 'wc_shipping_insurance_note_after_checkout');
function wc_shipping_insurance_note_after_checkout() {
global $woocommerce;
$product_id = 971;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found ):
?>
<tr class="shipping">
<th><?php _e( 'Gift wrapper', 'woocommerce' ); ?></th>
<td><?php _e( 'Add ($3)' ); ?> </td>
</tr>
<?php else: ?>
<tr class="shipping">
<th><?php _e( 'Gift wrapper', 'woocommerce' ); ?></th>
<td>$3</td>
</tr>
<?php endif;
}
Edit per comment. You could try something like this if you only want to add the table row if a product in the cart has a certain category.
You will have to change "example-category" in $categories = array('example-category'); to your category slug.
add_action('woocommerce_before_checkout_form','wc_shipping_insurance_note_after_checkout');
function wc_shipping_insurance_note_after_checkout() {
global $woocommerce;
$categories = array('example-category');
$found = false;
//loop trough cart items
foreach ( WC()->cart->get_cart_contents() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['product_id'];
//Check if product has category
if ( has_term( $categories, 'product_cat', $product_id ) ) {
$found = true;
}
}
// Do this if product has category
if ( $found ) {
?>
<tr class="shipping">
<th><?php _e( 'Gift wrapper', 'woocommerce' ); ?></th>
<td><?php _e( 'Add ($3)' ); ?> </td>
</tr>
<?php
} else {
//If product does not have category do this instead
?>
<tr class="shipping">
<th><?php _e( 'Gift wrapper', 'woocommerce' ); ?></th>
<td>$3</td>
</tr>
<?php
}
}

Related

Plugin to set out of stock product image doesn't work

I'm creating a plugin to set a different image for each out of stock product everything is displayed in the dashboard only if you set an image it doesn't work can someone help me solve the problem in the code, I would be very grateful
<?php
/**
* Plugin Name: Out of Stock Image Changer for WooCommerce
* Plugin URI:
* Description: Automatically changes the product image when it goes out of stock in WooCommerce
* Version: 1.0.0
* Author:
* Author URI:
* License:
*/
add_action( 'admin_menu', 'register_product_image_changer_page' );
function register_product_image_changer_page() {
add_submenu_page( 'edit.php?post_type=product', 'Out of stock images', 'Out of stock images', 'manage_options', 'out-of-stock-images', 'render_product_image_changer_page' );
}
function render_product_image_changer_page() {
global $wpdb;
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.', 'woocommerce' ) );
}
if ( ! empty( $_POST ) && check_admin_referer( 'update_out_of_stock_images' ) ) {
$product_ids = isset( $_POST['product_id'] ) ? $_POST['product_id'] : array();
$out_of_stock_images = isset( $_POST['out_of_stock_image'] ) ? $_POST['out_of_stock_image'] : array();
foreach ( $product_ids as $index => $product_id ) {
update_post_meta( $product_id, 'out_of_stock_image', $out_of_stock_images[ $index ] );
}
}
$results = $wpdb->get_results( "SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'product' AND post_status = 'publish'" );
?>
<div class="wrap">
<h1><?php _e( 'Out of stock images', 'woocommerce' ); ?></h1>
<form method="post">
<?php wp_nonce_field( 'update_out_of_stock_images' ); ?>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th><?php _e( 'Product', 'woocommerce' ); ?></th>
<th><?php _e( 'Out of stock image URL', 'woocommerce' ); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ( $results as $result ) : ?>
<tr>
<td><?php echo $result->post_title; ?></td>
<td>
<input type="hidden" name="product_id[]" value="<?php echo $result->ID; ?>">
<input type="text" name="out_of_stock_image[]" value="<?php echo get_post_meta( $result->ID, 'out_of_stock_image', true ); ?>" class="widefat">
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p class="submit">
<input type="submit" name="submit" id="submit" class="button button-primary" value="<?php _e( 'Save Changes', 'woocommerce' ); ?>">
</p>
</form>
</div>
<?php
}
add_action( 'woocommerce_before_single_product_summary', 'maybe_change_product_image', 9 );
function maybe_change_product_image() {
global $product;
if ( ! $product->is_in_stock() ) {
$out_of_stock_image = get_post_meta( get_the_ID(), 'out_of_stock_image', true );
if ( ! empty( $out_of_stock_image ) ) {
remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
add_action( 'woocommerce_before_single_product_summary', 'show_out_of_stock_image', 20 );
}
}
}
function show_out_of_stock_image() {
global $product;
$out_of_stock_image = get_post_meta( get_the_ID(), 'out_of_stock_image', true );
if ( ! empty( $out_of_stock_image ) ) {
echo '<img src="' . esc_url( $out_of_stock_image ) . '" class="attachment-shop_single size-shop_single wp-post-image" alt="">';
}
}
everything works in the dashboard, but if an image is set it is not displayed
this code worked for me.
/**
* Plugin Name: Out of Stock Image Changer for WooCommerce
* Plugin URI:
* Description: Automatically changes the product image when it goes out of stock in WooCommerce
* Version: 1.0.0
* Author:
* Author URI:
* License:
*/
add_action( 'admin_menu', 'register_product_image_changer_page' );
function register_product_image_changer_page() {
add_submenu_page( 'edit.php?post_type=product', 'Out of stock images', 'Out of stock images', 'manage_options', 'out-of-stock-images', 'render_product_image_changer_page' );
}
function render_product_image_changer_page() {
global $wpdb;
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.', 'woocommerce' ) );
}
if ( ! empty( $_POST ) && check_admin_referer( 'update_out_of_stock_images' ) ) {
$product_ids = isset( $_POST['product_id'] ) ? $_POST['product_id'] : array();
$out_of_stock_images = isset( $_POST['out_of_stock_image'] ) ? $_POST['out_of_stock_image'] : array();
foreach ( $product_ids as $index => $product_id ) {
update_post_meta( $product_id, 'out_of_stock_image', $out_of_stock_images[ $index ] );
}
}
$results = $wpdb->get_results( "SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'product' AND post_status = 'publish'" );
?>
<div class="wrap">
<h1><?php _e( 'Out of stock images', 'woocommerce' ); ?></h1>
<form method="post">
<?php wp_nonce_field( 'update_out_of_stock_images' ); ?>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th><?php _e( 'Product', 'woocommerce' ); ?></th>
<th><?php _e( 'Out of stock image URL', 'woocommerce' ); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ( $results as $result ) : ?>
<tr>
<td><?php echo $result->post_title; ?></td>
<td>
<input type="hidden" name="product_id[]" value="<?php echo $result->ID; ?>">
<input type="text" name="out_of_stock_image[]" value="<?php echo get_post_meta( $result->ID, 'out_of_stock_image', true ); ?>" class="widefat">
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p class="submit">
<input type="submit" name="submit" id="submit" class="button button-primary" value="<?php _e( 'Save Changes', 'woocommerce' ); ?>">
</p>
</form>
</div>
<?php
}
add_action( 'woocommerce_before_single_product', 'maybe_change_product_image', 9 );
function maybe_change_product_image() {
global $product;
if ( ! $product->is_in_stock() ) {
$out_of_stock_image = get_post_meta( $product->get_id(), 'out_of_stock_image', true );
if ( ! empty( $out_of_stock_image ) ) {
remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
add_action( 'woocommerce_before_single_product_summary', 'show_out_of_stock_image', 20 );
}
}
}
function show_out_of_stock_image() {
global $product;
$out_of_stock_image = get_post_meta( $product->get_id(), 'out_of_stock_image', true );
if ( ! empty( $out_of_stock_image ) ) {
echo '<img src="' . esc_url( $out_of_stock_image ) . '" class="attachment-shop_single size-shop_single wp-post-image" alt="">';
}
}

Displaying product category names in the WordPress order table (Woocommerce) [duplicate]

This question already has an answer here:
Show product categories in a new column on WooCommerce "My account" orders table
(1 answer)
Closed 1 year ago.
There are orders that have already been completed or not, and they contain goods, clothing, courses, etc. In WordPress, I have all the products subdivided into categories, but I don't know how to display the names of these categories. Suppose I have an order from a T-shirt and some course, and in the category I have to display "Clothes, Courses" (In the picture below, it is marked in red where it is necessary to display). I was able to display only the "Categories" tab, but the categories themselves cannot be displayed at all :( Here is the code from the orders.php file
<table class="woocommerce-orders-table woocommerce-MyAccount-orders shop_table shop_table_responsive my_account_orders account-orders-table">
<thead>
<tr>
<?php foreach ( wc_get_account_orders_columns() as $column_id => $column_name ) : ?>
<th class="woocommerce-orders-table__header woocommerce-orders-table__header-<?php echo esc_attr( $column_id ); ?>"><span class="nobr"><?php echo esc_html( $column_name ); ?></span></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php
foreach ( $customer_orders->orders as $customer_order ) {
$order = wc_get_order( $customer_order ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
$item_count = $order->get_item_count() - $order->get_item_count_refunded();
?>
<tr class="woocommerce-orders-table__row woocommerce-orders-table__row--status-<?php echo esc_attr( $order->get_status() ); ?> order">
<?php foreach ( wc_get_account_orders_columns() as $column_id => $column_name ) : ?>
<td class="woocommerce-orders-table__cell woocommerce-orders-table__cell-<?php echo esc_attr( $column_id ); ?>" data-title="<?php echo esc_attr( $column_name ); ?>">
<?php if ( has_action( 'woocommerce_my_account_my_orders_column_' . $column_id ) ) : ?>
<?php do_action( 'woocommerce_my_account_my_orders_column_' . $column_id, $order ); ?>
<?php elseif ( 'order-number' === $column_id ) : ?>
<a href="<?php echo esc_url( $order->get_view_order_url() ); ?>">
<?php echo esc_html( _x( '#', 'hash before order number', 'woocommerce' ) . $order->get_order_number() ); ?>
</a>
<?php elseif ( 'order-cat' === $column_id ) : ?>
<?php elseif ( 'order-date' === $column_id ) : ?>
<time datetime="<?php echo esc_attr( $order->get_date_created()->date( 'c' ) ); ?>"><?php echo esc_html( wc_format_datetime( $order->get_date_created() ) ); ?></time>
<?php elseif ( 'order-status' === $column_id ) : ?>
<?php echo esc_html( wc_get_order_status_name( $order->get_status() ) ); ?>
<?php elseif ( 'order-total' === $column_id ) : ?>
<?php
/* translators: 1: formatted order total 2: total order items */
echo wp_kses_post( sprintf( _n( '%1$s for %2$s item', '%1$s for %2$s items', $item_count, 'woocommerce' ), $order->get_formatted_order_total(), $item_count ) );
?>
<?php elseif ( 'order-actions' === $column_id ) : ?>
<?php
$actions = wc_get_account_orders_actions( $order );
if ( ! empty( $actions ) ) {
foreach ( $actions as $key => $action ) { // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
echo '' . esc_html( $action['name'] ) . '';
}
}
?>
<?php endif; ?>
</td>
<?php endforeach; ?>
</tr>
<?php
}
?>
</tbody>
</table>
And here is the picture:
enter image description here
$items = $order->get_items();
$cats = '';
foreach($items as $key => $item) {
$product_id = $item['product_id'];
$term_obj_list = get_the_terms($product_id, 'product_cat');
$terms_string = implode(', ', wp_list_pluck($term_obj_list, 'name'));
$cats .= $terms_string;
}
echo $cats;
Put this in correct elseif block of your given code.
Updated according to the comment with code comment:
//Getting all the items in the order
$items = $order->get_items();
$c_list = [];
/**
* Loop through all items and get their categories [a product can have multiple category]
*/
foreach($items as $key => $item) {
//We need the product id to retrieved the categories
$product_id = $item['product_id'];
//Retrieving all the categories that product has
$term_obj_list = get_the_terms($product_id, 'product_cat');
//Loop through all the categories the current product has and saving it in a array with category id as index
//so that if the save category is assigned to another product we do not get the duplicate category
foreach($term_obj_list as $term_obj) {
$c_list[$term_obj->term_id] = $term_obj->name;
}
}
//lastly we concatenating all the categories with ", "
$cats = implode(', ', $c_list);
//printing the final result
echo $cats;

If there is no discount hide table row in Woocommerce

I am trying to implement the code below when a discount is applied to an order on my Woocommerce store. Right now, it shows every time a product is added. I am discounting all orders 15% when 5 or more products are added to the cart. But if I only add 2 products the table row still shows (and it shows $40 which is odd). It works great when 5 or more items are added to the cart. Any help would be much appreciated.
<tr class="cart-subtotal">
<th><?php esc_html_e( '15% Discount', 'beaux' ); ?></th>
<td><?php esc_html_e( '-', 'beaux' ); ?><?php echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key ); ?></td>
</tr>
I think you did it using woocommerce templates, it's better to use hooks:
add_filter( 'woocommerce_cart_totals_order_total_html', 'ywp_custom_total_message_html' );
function ywp_custom_total_message_html( $value ) {
global $woocommerce;
$cart_item_count = $woocommerce->cart->cart_contents_count;
if( $cart_item_count >= 5 ) {
$value .= esc_html_e( '15% Discount', 'beaux' ) . '<br />';
}
return $value;
}
Code goes in functions.php of your active theme/child theme. Tested and works.
You can check the number of items in the cart using WC()->cart->get_cart_contents_count().
<?php if ( WC()->cart->get_cart_contents_count() >= 5 ): ?>
<tr class="cart-subtotal">
<th><?php esc_html_e( '15% Discount', 'beaux' ); ?></th>
<td><?php esc_html_e( '-', 'beaux' ); ?><?php echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key ); ?></td>
</tr>
<?php endif; ?>
Just replace your snippet by this one. If less than 5 items are in the cart, the discount won't show.

Get product custom attribute Woocommerce

I have a single product custom variation table template in functions.php and I'm trying to get product custom attribute. I have two them (date and location).
I'm found a lot of solutions, but none didn't work for me.
Woocommerce version 3.2.6.
With this code below I get
Notice: Only variables should be passed by reference.
And I get type 'Null' of $date.
<td class="date">
<?php
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
$date = array_shift( wc_get_product_terms( $product_id, 'pa_date', array( 'fields' => 'names' ) ) );
?>
</td>
This is my full product variation table code in function.php
function woocommerce_variable_add_to_cart(){
global $product, $post, $woocommerce;
$attributes = $product->get_attributes();
$variations = find_valid_variations();
// Check if the special 'price_grid' meta is set, if it is, load the default template:
if ( get_post_meta($post->ID, 'price_grid', true) ) {
wp_enqueue_script( 'wc-add-to-cart-variation' );
wc_get_template( 'single-product/add-to-cart/variable.php', array(
'available_variations' => $product->get_available_variations(),
'attributes' => $product->get_variation_attributes(),
'selected_attributes' => $product->get_variation_default_attributes()
) );
return;
}
?>
<table class="variations variations-grid" cellspacing="0">
<thead>
<tr>
<td> Date | Location </td>
<td> Price </td>
<td> Quantity </td>
<td> Availability </td>
<td> </td>
</tr>
</thead>
<tbody>
<?php
foreach ($variations as $key => $value) {
if( !$value['variation_is_visible'] ) continue;
?>
<tr>
<td class="date">
<?php
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id; // Added WC 3+ support
$date = array_shift( wc_get_product_terms( $product_id, 'pa_date', array( 'fields' => 'names' ) ) );
?>
</td>
<td class="price">
<?php echo '<span>£</span>' . $product->get_price(); ?>
</td>
<td class="quantity">
<?php woocommerce_quantity_input(); ?>
</td>
<td class="stock">
<?php if (!$value['is_in_stock'] ) { ?>
<p class="stock out-of-stock"><?php _e( 'Places Not Available', 'woocommerce' ); ?></p>
<?php } else { ?>
<p class="stock in-stock"><?php _e( 'Places Available', 'woocommerce' ); ?></p>
</td>
<td class="add-to-cart">
<form class="cart" action="<?php echo esc_url( $product->add_to_cart_url() ); ?>" method="post" enctype='multipart/form-data'>
<?php
if(!empty($value['attributes'])){
foreach ($value['attributes'] as $attr_key => $attr_value) {
?>
<input type="hidden" name="<?php echo $attr_key?>" value="<?php echo $attr_value?>">
<?php
}
}
?>
<button type="submit" class="single_add_to_cart_button button alt"><span class="glyphicon glyphicon-tag"></span> Add to cart</button>
<input type="hidden" name="variation_id" value="<?php echo $value['variation_id']?>" />
<input type="hidden" name="product_id" value="<?php echo esc_attr( $post->ID ); ?>" />
<input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $post->ID ); ?>" />
</form>
<?php } ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php
}
function find_valid_variations() {
global $product;
$variations = $product->get_available_variations();
$attributes = $product->get_attributes();
$new_variants = array();
foreach( $variations as $variation ) {
// Peruse the attributes.
// 1. If both are explicitly set, this is a valid variation
// 2. If one is not set, that means any, and we must 'create' the rest.
$valid = true; // so far
foreach( $attributes as $slug => $args ) {
if( array_key_exists("attribute_$slug", $variation['attributes']) && !empty($variation['attributes']["attribute_$slug"]) ) {
// Exists
} else {
// Not exists, create
$valid = false; // it contains 'anys'
foreach( explode( '|', $attributes[$slug]['value']) as $attribute ) {
$attribute = trim( $attribute );
$new_variant = $variation;
$new_variant['attributes']["attribute_$slug"] = $attribute;
$new_variants[] = $new_variant;
}
}
}
// This contains ALL set attributes, and is itself a 'valid' variation.
if( $valid )
$new_variants[] = $variation;
}
return $new_variants;
}
UPDATE
I got this code working, but I get both attribute values (date location) in one tag.
How to seperate attributes?
<td>
<?php
foreach($value['attributes'] as $key => $val ) {
$val = str_replace(array('-','_'), ' ', $val);
printf( '<span class="attr attr-%s">%s</span>', $key, ucwords($val) );
}
?>
</td>
UPDATE
Finally I get date and location but with extra warnings, notices, and single characters.
Code
<?php
foreach($value as $date ) {
printf($date['attribute_date']);
}
?>
** SOLVED **
Maybe not the best method, but it's working.
<td class="date">
<?php
$i = 0;
foreach($value['attributes'] as $key => $val ) {
if($i == 0 ) {
echo $val;
}
$i++;
}
?>
</td>
<td class="location">
<?php
$i = 0;
foreach($value['attributes'] as $key => $val ) {
if($i !== 0) {
echo $val;
}
$i++;
}
?>
</td>
Use the method get_attributes() and function wc_get_product_terms() described here
<?php
// Get the attributes
$attributes = $product->get_attributes();
// Start the loop
foreach ( $attributes as $attribute ) : ?>
<?php
// Check and output, adopted from /templates/single-product/product-attributes.php
if ( $attribute['is_taxonomy'] ) {
$values = wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' => 'names' ) );
echo apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values );
} else {
// Convert pipes to commas and display values
$values = array_map( 'trim', explode( WC_DELIMITER, $attribute['value'] ) );
echo apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values );
}
?>
<?php endforeach; ?>
If you look at the template \templates\single-product\product-attributes.php you can see how to get the individual attribute names.
if ( $attribute->is_taxonomy() ) {
$attribute_taxonomy = $attribute->get_taxonomy_object();
$attribute_values = wc_get_product_terms( $product->get_id(), $attribute->get_name(), array( 'fields' => 'all' ) );
foreach ( $attribute_values as $attribute_value ) {
$value_name = esc_html( $attribute_value->name );
if ( $attribute_taxonomy->attribute_public ) {
$values[] = '' . $value_name . '';
} else {
$values[] = $value_name;
}
}
}
Here's how to get specific Custom Attribute:
// Get the custom attribute
$svd_attribute = array_shift( wc_get_product_terms( $product->id, 'your_custom_attribute', array( 'fields' => 'names' ) ) );
// Display if String
if ( is_string( $svd_attribute ) ) {
echo wp_kses_post( "$svd_attribute" );
}
Just replace "your_custom_attribute"
Working on WooCommerce: 3.8.0

Wordpress/WooCommerce Registration

I'm using a plugin (User Profiles Made Easy) that allows a user to choose their own role when registering on my website. It does a good job with that, but what it doesn't do is allow me to conditionally show/hide other fields based on the role they choose.
I thought of Gravity Form and their User Registration add-on, but it won't allow the user to choose their own role when registering.
The WooCommerce tie-in is this: When the buyer checks out, I could collect the extra data at that time (instead of during registration), but I would want to only show the fields relevant to their chosen role. Any ideas?
Borrowing from my tutorial on cutomizing WooCommerce checkout I think we can just wrap certain fields role/capability conditional logica via current_user_can().
// Add a new checkout field
function kia_filter_checkout_fields($fields){
if( current_user_can('some_capability' ) ){
$fields['extra_fields'] = array(
'some_field' => array(
'type' => 'text',
'required' => true,
'label' => __( 'Some field' )
)
);
}
return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'kia_filter_checkout_fields' );
// display the extra field on the checkout form
function kia_extra_checkout_fields(){
if( current_user_can('some_capability' ) ){
$checkout = WC()->checkout(); ?>
<div class="extra-fields">
<h3><?php _e( 'Additional Fields' ); ?></h3>
<?php foreach ( $checkout->checkout_fields['extra_fields'] as $key => $field ) : ?>
<?php woocommerce_form_field( $key, $field, $checkout->get_value( $key ) ); ?>
<?php endforeach; ?>
<?php } ?>
</div>
<?php }
add_action( 'woocommerce_checkout_after_customer_details' ,'kia_extra_checkout_fields' );
// save the extra field when checkout is processed
function kia_save_extra_checkout_fields( $order_id, $posted ){
if( current_user_can( 'some_capability' && isset( $posted['some_field'] ) ) {
update_post_meta( $order_id, '_some_field', sanitize_text_field( $posted['some_field'] ) );
}
}
add_action( 'woocommerce_checkout_update_order_meta', 'kia_save_extra_checkout_fields', 10, 2 );
// display the extra data on order recieved page and my-account order review
function kia_display_order_data( $order_id ){
if( current_user_can('some_capability' ) ){
?>
<h2><?php _e( 'Additional Info' ); ?></h2>
<table class="shop_table shop_table_responsive additional_info">
<tbody>
<tr>
<th><?php _e( 'Some Field:' ); ?></th>
<td data-title="Telephone"><?php echo get_post_meta( $order_id, '_some_field', true ); ?></td>
</tr>
</tbody>
</table>
<?php }
}
add_action( 'woocommerce_thankyou', 'kia_display_order_data', 20 );
add_action( 'woocommerce_view_order', 'kia_display_order_data', 20 );
// display the extra data in the order admin panel
function kia_display_order_data_in_admin( $order ){
if( current_user_can('some_capability' ) ){
?>
<div class="order_data_column">
<h4><?php _e( 'Extra Details', 'woocommerce' ); ?></h4>
<?php
echo '<p><strong>' . __( 'Some field' ) . ':</strong>' . get_post_meta( $order->id, '_some_field', true ) . '</p>'; ?>
</div>
<?php }
}
add_action( 'woocommerce_admin_order_data_after_order_details', 'kia_display_order_data_in_admin' );

Resources