I’m trying to create a function inside WordPress to deploy in WooCommerce, so customers can look up for articles they’ve purchased by SKU or name.
The issue: is not working properly since no matter which SKU look for but same results are displayed. In addition to that, the amount of articles purchases it’s always 1 as result.
function search_orders_by_sku_or_product_name_form() {
ob_start();
?>
<form method="post" action="">
<input type="text" name="order_search" placeholder="enter SKU o name">
<input type="submit" value="Search">
</form>
<?php
return ob_get_clean();
}
add_shortcode('order_search_form', 'search_orders_by_sku_or_product_name_form');
function search_orders_by_sku_or_product_name_result() {
if (isset($_POST['order_search']) && !empty($_POST['order_search'])) {
$search_term = sanitize_text_field($_POST['order_search']);
$user_id = get_current_user_id();
$orders = wc_get_orders(array(
'customer' => $user_id,
'limit' => -1,
));
$found_orders = array();
foreach ($orders as $order) {
$order_items = $order->get_items();
foreach ($order_items as $item) {
$product = $item->get_product();
if (!$product) {
continue;
}
$sku = $product->get_sku();
$name = $product->get_name();
if ($sku && $name && (strpos($sku, $search_term) === 0 || strpos($name, $search_term) === 0)) {
$found_orders[] = $order;
break;
}
}
}
if (!empty($found_orders)) {
echo '<table>';
echo '<tr><th>Order</th><th>Status</th><th>SKU</th><th>Name</th><th>Quantity</th><th>Date</th></tr>';
foreach ($found_orders as $order) {
$order_data = $order->get_data();
$order_date = $order->get_date_created();
$formatted_date = $order_date->format('d/m/Y H:i');
$order_status = wc_get_order_status_name($order_data['status']);
echo '<tr>';
echo '<td>#' . $order_data['id'] . '</td>';
echo '<td>' . $order_status . '</td>';
echo '<td>' . $sku . '</td>';
echo '<td>' . $name . '</td>';
echo '<td>' . $item->get_quantity() . '</td>';
echo '<td>' . $formatted_date . ' Hs.</td>';
echo '</tr>';
}
echo '</table>';
} else {
echo 'Sorry no results.';
}
}
}
add_shortcode('order_search_result', 'search_orders_by_sku_or_product_name_result');
Any hint on how to make it work?
2
Answers
Try to use this code and check:
Try to replace your 2nd function with the following, that will allow you to get customer orders with correct quantity, product name and SKU (your first function stays unchanged):
Code goes in functions.php file of your child theme (or in a plugin). tested and works.