trouble with getting tax rate name in woocommerce - woocommerce

Hi currently i want to get the name of the tax rate in woocommerce. I there any way to get the value that is circled in this picture: http://i.imgur.com/niSraFa.png
My current code:
$items = $order->get_items();
$lineItem = array();
$productInfo = $orderInfo = array();
$order_items = array();
if ($items) foreach ($items as $item_key => $item_value) {
$_tax = new WC_Tax();
$_product = $order->get_product_from_item( $item_value );
$product_tax_class = $_product->get_tax_class();
$tax_class = $item_value['tax_class'];

You would use the WC_Tax()->find_rates() method. It takes an array as an argument, which in your case would be array( 'country' => 'NO' ) and returns an array of matching tax rates. One of the keys of this array is label which contains the name of the tax rate.
$tax = new WC_Tax();
$country_code = 'NO'; // or populate from order to get applicable rates
$rates = $tax->find_rates( array( 'country' => $country_code ) );
foreach( $rates as $rate ){
$tax_rate_name = $rate['label'];
}
To find the applicable tax rates for a specific order, populate the array for find_rates() with values from the shipping/billing address on the order.

Related

See last order on specific product

Hi how to see last order of specific product in woocommerce?
EXEMPLE:
PRODUCT NAME
PRICE 10 $ [ADD CART]
LAST ORDER
DATE QUT. PRICE
10.10.2021 2 9$
10.12.2021 6 3$
10.01.2022 39 5$
EDIT: I would like to place it on the product page and as a second viewer user sees his latest product orders.
Place the following function in your functions.php file
function latest_order_by_product_id() {
global $wpdb;
// Select Product ID
$product_id = 14;
$orders_statuses = "'wc-completed', 'wc-processing', 'wc-on-hold'";
//Change get_row to get_col if you want all orders
//Change DESC to ASC if we need reverse order
$orders = $wpdb->get_row("
SELECT DISTINCT woi.order_id FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim,
{$wpdb->prefix}woocommerce_order_items as woi,
{$wpdb->prefix}posts as p WHERE woi.order_item_id = woim.order_item_id AND woi.order_id = p.ID
AND p.post_status IN ( $orders_statuses ) AND woim.meta_key IN ( '_product_id', '_variation_id' ) AND woim.meta_value LIKE '$product_id' ORDER BY woi.order_item_id DESC");
if($orders):
$data = array();
foreach($orders as $key => $order_id):
$order = wc_get_order( $order_id );
if ( $order ):
$data[$key]['order_date'] = $order_date = $order->get_date_completed(); // Change depending on type of date you are looking for - get_date_created(), get_date_completed(), get_date_paid()
//Loop order items
foreach ( $order->get_items() as $item_id => $item ):
if($product_id == $item->get_product_id()):
$data[$key]['qty'] = $product_qty = $item->get_quantity();
//Choose which price you want to get
$data[$key]['price'] = $product_price = $item->get_total() + $item->get_total_tax(); // Discounted total with tax
//OR
//$product_price = $item->get_subtotal() + $item->get_subtotal_tax(); // NON discounted total with tax
endif;
endforeach;
endif;
endforeach;
endif;
if($data):
$output = array();
$output[] .='<table><thead><tr><th>LAST ORDER DATE</th><th>QTY</th><th>PRICE</th></tr></theead><tbody>';
foreach($data as $order_data):
//Change date format if needed
$date = $order_data['order_date']->date("d.m.Y");
$output[] .= '<tr><td>'.$date.'</td><td>'.$order_data['qty'].'</td><td>'.$order_data['price'].'</td></tr>';
endforeach;
$output[] .= '</tbody></table>';
endif;
echo sprintf('%s',implode($output));
}
Call latest_order_by_product_id() where you need it. Result - https://prnt.sc/6AhgTPXFerBg
Example with shortcode. How to use [lobpid product_id="35"]
add_shortcode('lobpid','latest_order_by_product_id' );
function latest_order_by_product_id($attr) {
global $wpdb;
$args = shortcode_atts( array(
'product_id' => '',
), $attr );
// Select Product ID
$product_id = $args['product_id'];
//Skip the rest if we dont have product id defined
if(empty($product_id)): echo 'there is no product id defined'; return; endif;
$orders_statuses = "'wc-completed', 'wc-processing', 'wc-on-hold'";
//Change get_row to get_col if you want all orders
//Change DESC to ASC if we need reverse order
$orders = $wpdb->get_row("
SELECT DISTINCT woi.order_id FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim,
{$wpdb->prefix}woocommerce_order_items as woi,
{$wpdb->prefix}posts as p WHERE woi.order_item_id = woim.order_item_id AND woi.order_id = p.ID
AND p.post_status IN ( $orders_statuses ) AND woim.meta_key IN ( '_product_id', '_variation_id' ) AND woim.meta_value LIKE '$product_id' ORDER BY woi.order_item_id DESC");
//Skip the rest if we dont have orders
if(empty($orders)): echo 'no orders found'; return; endif;
if($orders):
$data = array();
foreach($orders as $key => $order_id):
$order = wc_get_order( $order_id );
if ( $order ):
$data[$key]['order_date'] = $order_date = $order->get_date_completed(); // Change depending on type of date you are looking for - get_date_created(), get_date_completed(), get_date_paid()
//Loop order items
foreach ( $order->get_items() as $item_id => $item ):
if($product_id == $item->get_product_id()):
$data[$key]['qty'] = $product_qty = $item->get_quantity();
//Choose which price you want to get
$data[$key]['price'] = $product_price = $item->get_total() + $item->get_total_tax(); // Discounted total with tax
//OR
//$product_price = $item->get_subtotal() + $item->get_subtotal_tax(); // NON discounted total with tax
endif;
endforeach;
endif;
endforeach;
endif;
if($data):
$output = array();
$output[] .='<table><thead><tr><th>LAST ORDER DATE</th><th>QTY</th><th>PRICE</th></tr></theead><tbody>';
foreach($data as $order_data):
//Change date format if needed
$date = $order_data['order_date']->date("d.m.Y");
$output[] .= '<tr><td>'.$date.'</td><td>'.$order_data['qty'].'</td><td>'.$order_data['price'].'</td></tr>';
endforeach;
$output[] .= '</tbody></table>';
endif;
echo sprintf('%s',implode($output));
}

Woocommerce Order cart array by cat and sub cat

Hi we are trying to sort the Woo Cart by Main product category and list under the products in that category. Like below:
Wheel Parts
spokes 12
Tyre's
Frame
Y Frame
X Frame
Z Frame
Seat
Seat 1
Seat 2
We have managed to get to display by cat order but it is not ordering them into Main Cat -> Sub Cat
We have the below code and trying to order cart array by cat and sub cat
add_action( 'woocommerce_cart_loaded_from_session', function() {
global $woocommerce;
$products_in_cart = array();
foreach ( $woocommerce->cart->cart_contents as $key => $item ) {
$terms = wp_get_post_terms($item['data']->id, 'product_cat' );
$products_in_cart[ $key ] = $terms[0]->name;
}
natsort( $products_in_cart );
$cart_contents = array();
foreach ( $products_in_cart as $cart_key => $product_title ) {
$cart_contents[ $cart_key ] = $woocommerce->cart->cart_contents[ $cart_key ];
}
$woocommerce->cart->cart_contents = $cart_contents;
}, 100 );
Any one have any ideas please?
Your code was correct but you had just natsort which returning 1 is causing the issue. You also need to sort categories by menu order. Please check the below code working perfectly.
add_action( 'woocommerce_cart_loaded_from_session', function() {
global $woocommerce;
$products_in_cart = array();
foreach ( $woocommerce->cart->cart_contents as $key => $item ) {
$terms = wp_get_post_terms($item['data']->id, 'product_cat' );
$products_in_cart[ $key ] = $terms[0]->term_id;
}
// $categories = get_terms( 'product_cat', 'orderby=menu_order&hide_empty=1' );
asort($products_in_cart);
$cat_array = array();
foreach ($products_in_cart as $key => $value) {
$cat_array[$key] =get_term_by('id', $value, 'product_cat');
}
$mai_cat = [];
$i=0;
foreach ($cat_array as $parent_key => $parent_value) {
if($parent_value->parent == 0)
{
$mai_cat[$parent_key] = $parent_value->term_id;
foreach ($cat_array as $parent_key_sub => $parent_value_sub) {
if($parent_value_sub->parent == $parent_value->term_id)
{
$mai_cat[$parent_key_sub] = $parent_value_sub->term_id;
}
}
}
}
$cart_contents = array();
foreach ( $mai_cat as $cart_key => $product_title ) {
$cart_contents[ $cart_key ] = $woocommerce->cart->cart_contents[ $cart_key ];
}
$woocommerce->cart->cart_contents = $cart_contents;
}, 100 );
Tested and works well

Woocommerce get order item meta

I'm using the woocommerce_checkout_create_order_line_item action to update/add some order item meta data.
At the same time, within the same function, I want to use wc_get_order_item_meta to get a different meta value from the same item but I can't get it to work within this action hook.
I think the issue is that I'm not managing to get the $item_id needed to use wc_get_order_item_meta.
Am I going about this in the wrong way?
I've tried the method here How to get order items ids to get some product meta data?
Below code will return all details of order with order item meta.just take those values in count which you want to use remove others.
function action_woocommerce_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
$order_id = $order->get_order_number();
$order = wc_get_order( $order_id );
$order_data = $order->get_data();
//Order Data and order item metas
$order_id = $order_data['id'];
$order_parent_id = $order_data['parent_id'];
$order_status = $order_data['status'];
$order_currency = $order_data['currency'];
$order_version = $order_data['version'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method_title = $order_data['payment_method_title'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method = $order_data['payment_method'];
## Creation and modified WC_DateTime Object date string ##
// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');
// Using a timestamp ( with php getTimestamp() function as method)
$order_timestamp_created = $order_data['date_created']->getTimestamp();
$order_timestamp_modified = $order_data['date_modified']->getTimestamp();
$order_discount_total = $order_data['discount_total'];
$order_discount_tax = $order_data['discount_tax'];
$order_shipping_total = $order_data['shipping_total'];
$order_shipping_tax = $order_data['shipping_tax'];
$order_total = $order_data['cart_tax'];
$order_total_tax = $order_data['total_tax'];
$order_customer_id = $order_data['customer_id']; // ... and so on
## BILLING INFORMATION:
$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_company = $order_data['billing']['company'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];
## SHIPPING INFORMATION:
$order_shipping_first_name = $order_data['shipping']['first_name'];
$order_shipping_last_name = $order_data['shipping']['last_name'];
$order_shipping_company = $order_data['shipping']['company'];
$order_shipping_address_1 = $order_data['shipping']['address_1'];
$order_shipping_address_2 = $order_data['shipping']['address_2'];
$order_shipping_city = $order_data['shipping']['city'];
$order_shipping_state = $order_data['shipping']['state'];
$order_shipping_postcode = $order_data['shipping']['postcode'];
$order_shipping_country = $order_data['shipping']['country'];
};
//To get Order item metas please use below code
foreach ($order->get_items() as $item_key => $item_values):
## Using WC_Order_Item methods ##
// Item ID is directly accessible from the $item_key in the foreach loop or
$item_id = $item_values->get_id();
## Using WC_Order_Item_Product methods ##
$item_name = $item_values->get_name(); // Name of the product
$item_type = $item_values->get_type(); // Type of the order item ("line_item")
$product_id = $item_values->get_product_id(); // the Product id
$wc_product = $item_values->get_product(); // the WC_Product object
## Access Order Items data properties (in an array of values) ##
$item_data = $item_values->get_data();
$product_name = $item_data['name'];
$product_id = $item_data['product_id'];
$variation_id = $item_data['variation_id'];
$quantity = $item_data['quantity'];
$tax_class = $item_data['tax_class'];
$line_subtotal = $item_data['subtotal'];
$line_subtotal_tax = $item_data['subtotal_tax'];
$line_total = $item_data['total'];
$line_total_tax = $item_data['total_tax'];
endforeach;
// add the action
add_action( 'woocommerce_checkout_create_order_line_item', 'action_woocommerce_checkout_create_order_line_item', 10, 4 );

Find time between order marked as processing to order marked as completed

I want to find the time from order processing to order marked as complete for every order. How can I get that? I have read this and it only gives time for last modified.
This will get all the orders and return the number of seconds between the order being placed and if it is currently at a completed status. You haven't specified a format for the time difference so I have just returned it as a string with the corresponding order id.
$query = new WC_Order_Query( array(
'limit' => -1,
'orderby' => 'date',
'order' => 'DESC',
'return' => 'ids',
) );
foreach( $query->get_orders() as $order_id ) {
$order = wc_get_order($order_id);
if( $order->get_status() === 'completed') {
$order_data = $order->get_data();
$timestamp = $order_data['date_modified']->getTimestamp() - $order_data['date_created']->getTimestamp();
$d1 = new DateTime();
$d2 = new DateTime();
$d2->add(new DateInterval('PT'.$timestamp.'S'));
$order_interval = $d2->diff($d1);
echo 'Order ID : ' . $order->get_id() . ' ' . $order_interval->format('%a days, %h hours, %i minutes and %s seconds');
}
}
have you tried this?
$order_id = 1945;
$order = new WC_Order($order_id);
$order_data = $order->get_data();
$date1 = $order_data['date_created']->date( 'Y-m-d G:i:s' );
$date2 = $order_data['date_modified']->date( 'Y-m-d G:i:s' );
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
printf("%d years, %d months, %d days\n", $years, $months, $days);
You can improved this by adding a check for the status of the order.

How to limit query in price filter

How to limit query to 6 in woocommerce product price filter short-code [products_by_price min="100" max="300"]? The code below is based on woocommerce product short-code which unfortunately does not support per_page. In this case I need to limit query to 6 to avoid showing all products.
add_shortcode( 'wc_products_price_range', 'wc_products_price_range' );
function wc_products_price_range( $atts, $content, $shortcode ) {
if ( class_exists( 'WooCommerce' ) ) {
$shortcodes = new WC_Shortcodes();
if ( is_array( $atts ) ) {
$min = (int) $atts['min'];
$max = (int) $atts['max'];
if ( $min && $max ) {
$and = "meta_value BETWEEN $min AND $max";
} else {
if ( $min ) {
$and = "meta_value >= $min";
} elseif ( $max ) {
$and = "meta_value <= $max";
}
}
if ( $and ) {
global $wpdb;
$query = "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_price' AND $and";
$ids = $wpdb->get_col( $query );
if ( ! empty( $ids ) ) {
$atts['ids'] = implode( ",", $ids );
}
}
}
return $shortcodes->products( $atts );
}
}
After a quick scan of WC shortcode class I have came across this :
public static function products( $atts ) {
$atts = shortcode_atts( array(
'columns' => '4',
'orderby' => 'title',
'order' => 'asc',
'ids' => '',
'skus' => ''
), $atts );
it means you can pass 'column' attribute along with ids where you can limit posts per page.
and in this query :
$query = "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_price' AND $and";
you can use limit 0,6 with order by clause.
Hope this helps.
OR
random rows:
SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT 1;
or you can pass 'rand' to attributes in shortcode.

Resources