My intention is to hide orders that contains a specific product id (5).
This in the WooCommmerce "My account" orders table
What I have done are the steps as described in the /myaccount/orders.php
template file. Namely copied the file to my theme folder.
(mytheme/woocommerce/myaccount/orders.php
.)
There I replaced
<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">
...
</tr>
<?php
}
?>
</tbody>
With
<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();
foreach( $order->get_items() as $item ) {
$product_id = $item->get_product_id();
if ( $product_id != 5 ) {
?>
<tr class="woocommerce-orders-table__row
woocommerce-orders-table__row--status-<?php echo esc_attr(
$order->get_status() ); ?> order">
...
</tr>
<?php
}
}
}
?>
</tbody>
Although this has no error messages, it does not produce the desired result.
Can someone give some advice? oh, and if there is a solution via hooks instead of
overwriting the template file I’d really appreciate it.
2
Answers
To answer your question via hooks, you can use the
woocommerce_my_account_my_orders_query
filter hook.The code below is copied from /includes/wc-template-functions.php line 3159 – 3185 @version 2.5.0
As you can see, via the hook, you can modify the arguments used by the
wc_get_orders
function. Which in turn is used by thewc_get_template
function. The function that calls the /myaccount/orders.php template file and pass the arguments.wc_get_orders
allows us to exclude orderIDs. But no productIDs. That’s why we’re going to use a workaround so we can still pass the necessary orderIDs to exclude as argument.The function to get all orders IDs for a given product ID, processed in my answer is based on Woocommerce: Get all orders for a product answer code.
So to answer your question, you get:
If you look at WC_Order->get_items this retuns WC_Order_Item not always WC_Order_Item_Product (which has get_product_id). So I would try something like this: