See last order on specific product - wordpress

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));
}

Related

Update Parent Product Quantity When Variation Quantity Changes

I am actually trying to update the stock quantity of parent products whenever the quantity of any of its variation increases or decreases.
What could be the error in following code.
function wc_get_variable_product_stock_quantity( $output = 'raw', $product_id = 0 ){
global $wpdb, $product;
// Get the product ID (can be defined)
$product_id = $product_id > 0 ? $product_id : get_the_id();
// Check and get the instance of the WC_Product Object
$product = is_a( $product, 'WC_Product' ) ? $product : wc_get_product($product_id);
// Only for variable product type
if( $product->is_type('variable') ){
// Get the stock quantity sum of all product variations (children)
$stock_quantity = $wpdb->get_var("
SELECT SUM(pm.meta_value)
FROM {$wpdb->prefix}posts as p
JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
WHERE p.post_type = 'product_variation'
AND p.post_status = 'publish'
AND p.post_parent = '$product_id'
AND pm.meta_key = '_stock'
AND pm.meta_value IS NOT NULL
");
// Preparing formatted output
if ( $stock_quantity > 0 ) {
$html = '<p class="stock in-stock">'. sprintf( __("%s in stock", "woocommerce"), $stock_quantity ).'</p>';
} else {
if ( is_numeric($stock_quantity) )
$html = '<p class="stock out-of-stock">' . __("Out of stock", "woocommerce") . '</p>';
else
$html = '';
}
// Different output options
if( $output == 'echo_html' )
echo $html;
elseif( $output == 'return_html' )
return $html;
else
return $stock_quantity;
}
}

Update Product Stock When Variation Stock Changes in WooCommerce

I am trying the update total stock of the product when stock for any variation changes. I want to keep the total stock of all the variations updated.
Here is the code I am using but it's not working. What could be the reason.
add_action( 'woocommerce_product_set_stock', 'wc_get_variable_product_stock_quantity' );
function wc_get_variable_product_stock_quantity( $output = 'raw', $product_id = 0 ){
global $wpdb, $product;
// Get the product ID (can be defined)
$product_id = $product_id > 0 ? $product_id : get_the_id();
// Check and get the instance of the WC_Product Object
$product = is_a( $product, 'WC_Product' ) ? $product : wc_get_product($product_id);
// Only for variable product type
if( $product->is_type('variable') ){
// Get the stock quantity sum of all product variations (children)
$stock_quantity = $wpdb->get_var("
SELECT SUM(pm.meta_value)
FROM {$wpdb->prefix}posts as p
JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
WHERE p.post_type = 'product_variation'
AND p.post_status = 'publish'
AND p.post_parent = '$product_id'
AND pm.meta_key = '_stock'
AND pm.meta_value IS NOT NULL
");
// Preparing formatted output
if ( $stock_quantity > 0 ) {
$html = '<p class="stock in-stock">'. sprintf( __("%s in stock", "woocommerce"), $stock_quantity ).'</p>';
} else {
if ( is_numeric($stock_quantity) )
$html = '<p class="stock out-of-stock">' . __("Out of stock", "woocommerce") . '</p>';
else
$html = '';
}
// Different output options
if( $output == 'echo_html' )
echo $html;
elseif( $output == 'return_html' )
return $html;
else
return $stock_quantity;
set_stock_quantity( $stock_quantity );
}
}

woocommerce variable product price on dropdown

Hello I m trying to make available the prices for the variations on the dropdown, at some point I were able to achieve it when were only one variable, but now I have two variables for the product but the price on the dropdown is not updating.
Based on Variable product attribute: Customizing each displayed radio buttons text value answer code, here is the code I use to get on the first step, but I need help to update the price of variations up to the second variable selected.
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
function display_price_in_variation_option_name( $term ) {
global $wpdb, $product;
if ( empty( $term ) ) return $term;
if ( empty( $product->id ) ) return $term;
$id = $product->get_id();
$result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name = '$term'" );
$term_slug = ( !empty( $result ) ) ? $result[0] : $term;
$query = "SELECT postmeta.post_id AS product_id
FROM {$wpdb->prefix}postmeta AS postmeta
LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postmeta.post_id )
WHERE postmeta.meta_key LIKE 'attribute_%'
AND postmeta.meta_key != 'attribute_pa_alto'
AND postmeta.meta_value = '$term_slug'
AND products.post_parent = $id";
$variation_id = $wpdb->get_col( $query );
$parent = wp_get_post_parent_id( $variation_id[0] );
if ( $parent > 0 ) {
$_product = new WC_Product_Variation( $variation_id[0] );
//EDITADO PARA MOSTRAR CUANDO NO HAY STOCK MUESTRA AGOTADO
if($_product->managing_stock() && $_product->get_stock_quantity() < 1){
return $term . ' - AGOTADO';
}else{
return $term . ' - (' . wp_kses( woocommerce_price( $_product->get_price() ), array() ) . ')';
}
}
return $term;
}

Woocommerce Calculate amount by customer input in product page

In product page to get input from customer as number of words. To calculate the amount from products add-ons fixed amount to additional 10$ for each above 500 words.
ex: 1. Number of Words: 530
Normal Price + additional price: 180$ + 10$
Total: 190$
Number of Words: 1040
Normal Price + additional price: 180$ + 20$
Total: 200$
This process as to create dynamic input form customer to calculate amount the price and total amount.
`$extra_amount = (int)'10';
$amount = (int)'180'; // how to get amount from woocommerce data
if(isset($_POST['wordnumber'])){ // how to get this paramater form woocommerce post values
$test =$_POST['wordnumber'];
$original_amount = '';
if($test <= (int)'500'){
$original_amount = $amount;
}
elseif($test > (int)'500'){
$div_amount = $test/(int)'500';
$round = floor($div_amount);
//echo '<br/>';
$total_extra = $round*$extra_amount;
$original_amount = $amount+$total_extra;
}
echo $original_amount;
}`
I installed WC Fields Factory plugin then i got value from one field using key. in that i written a function and i overrided the price value.
function calculate_gift_wrap_fee( $cart_object ) {
/* Gift wrap price */
$additionalPrice = 10;
foreach ( $cart_object->cart_contents as $key => $value ) {
$test = $value['custom field'];
if( $test <= 100 ) {
$quantity = floatval( $value['quantity'] );
$orgPrice = floatval( $value['data']->price );
$value['data']->price = ( $orgPrice );
}
elseif( $test > 100 ) {
$div_amount = floatval($test/500);
$round = floor($div_amount);
$total_extra = floatval($round * $additionalPrice);
$quantity = floatval( $value['quantity'] );
$orgPrice = floatval( $value['data']->price );
$pp = ($value['price']);
$total = floatval($pp + $total_extra);
$value['data']->price = ( $orgPrice + $total );
}
}}
add_action( 'woocommerce_before_calculate_totals', calculate_gift_wrap_fee', 1, 1 );

Break Up WordPress Archive List into Multiple Columns

I want to break up this archive list into multiple columns (three columns)...I don't want to use CSS3 for this. I can easily do this with wp_list_categories, but that method doesn't work with wp_get_archives.
Ideally, I'd like to implement a counter to add in tags at an approximate 1/3 count...then I can use CSS for the rest.
CUSTOM ARCHIVE FUNCTION:
function wp_custom_archive($args = '') {
global $wpdb, $wp_locale;
$defaults = array(
'limit' => '',
'format' => 'html', 'before' => '',
'after' => '', 'show_post_count' => false,
'echo' => 1
);
$r = wp_parse_args( $args, $defaults );
extract( $r, EXTR_SKIP );
if ( '' != $limit ) {
$limit = absint($limit);
$limit = ' LIMIT '.$limit;
}
// over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
$archive_date_format_over_ride = 0;
// options for daily archive (only if you over-ride the general date format)
$archive_day_date_format = 'Y/m/d';
// options for weekly archive (only if you over-ride the general date format)
$archive_week_start_date_format = 'Y/m/d';
$archive_week_end_date_format = 'Y/m/d';
if ( !$archive_date_format_over_ride ) {
$archive_day_date_format = get_option('date_format');
$archive_week_start_date_format = get_option('date_format');
$archive_week_end_date_format = get_option('date_format');
}
//filters
$where = apply_filters('customarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r );
$join = apply_filters('customarchives_join', "", $r);
$output = '<ul>';
$query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC $limit";
$key = md5($query);
$cache = wp_cache_get( 'wp_custom_archive' , 'general');
if ( !isset( $cache[ $key ] ) ) {
$arcresults = $wpdb->get_results($query);
$cache[ $key ] = $arcresults;
wp_cache_set( 'wp_custom_archive', $cache, 'general' );
} else {
$arcresults = $cache[ $key ];
}
if ( $arcresults ) {
$afterafter = $after;
foreach ( (array) $arcresults as $arcresult ) {
$url = get_month_link( $arcresult->year, $arcresult->month );
/* translators: 1: month name, 2: 4-digit year */
$text = sprintf(__('%s'), $wp_locale->get_month($arcresult->month));
$year_text = sprintf('<li>%d</li>', $arcresult->year);
if ( $show_post_count )
$after = ' ('.$arcresult->posts.')' . $afterafter;
$output .= ( $arcresult->year != $temp_year ) ? $year_text : '';
$output .= get_archives_link($url, $text, $format, $before, $after);
$temp_year = $arcresult->year;
}
}
$output .= '</ul>';
if ( $echo )
echo $output;
else
return $output;
}
CURRENT HTML OUTPUT (shortened):
<ul>
<li>2012</li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/09/' title='September'>September</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/08/' title='August'>August</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/07/' title='July'>July</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/06/' title='June'>June</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/05/' title='May'>May</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/04/' title='April'>April</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/03/' title='March'>March</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/02/' title='February'>February</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/01/' title='January'>January</a></li>
</ul>
If I understand correctly, you would have to do something like this
$output = '<ul class="col1">';
if ( $arcresults ) {
$numarticles = count($arcresults);
$column1 = round($numarticles/3);
$column2 = round($column1*2);
$counter = 0;
$afterafter = $after;
foreach ( (array) $arcresults as $arcresult ) {
if($counter == $column1) {
$output .= "</ul><ul class='col2'>";
} elseif($counter == $column2) {
$output .= "</ul><ul class='col3'>";
}
$url = get_month_link( $arcresult->year, $arcresult->month );
/* translators: 1: month name, 2: 4-digit year */
$text = sprintf(__('%s'), $wp_locale->get_month($arcresult->month));
$year_text = sprintf('<li>%d</li>', $arcresult->year);
if ( $show_post_count )
$after = ' ('.$arcresult->posts.')' . $afterafter;
$output .= ( $arcresult->year != $temp_year ) ? $year_text : '';
$output .= get_archives_link($url, $text, $format, $before, $after);
$temp_year = $arcresult->year;
$counter ++;
}
$output .= '</ul>';
}
This way, when the counter gets to a third of the way, it will add another list, so at the end you will have 3 lists.
Hope this helps.

Resources