Search code examples
phpsqlwordpresswoocommerceorders

Hide WooCommerce My Account Orders if the total purchased amount equal 0


In woocommerce, I am trying to hide the orders if there total is 0. Here is my code, but it does not work. Any idea about the problem?

add_filter( 'woocommerce_my_account_my_orders_query', 
'hide_zero_total_orders_from_my_account', 10, 1 );
function hide_zero_total_orders_from_my_account( $args ) {
$args['meta_query'] = array(
    array(
        'key'     => '_order_total',
        'value'   => 0,
        'compare' => '>',
        'type'    => 'NUMERIC',
    ),
);
return $args;
}

Solution

  • You can use instead a lightweight SQL query to get customer total purchases and use that query to hide My account Orders section if the total purchases amount is equal to 0 (zero):

    // Get customer purchases total amount
    function get_customer_purchases_total_amount(){
        global $wpdb;
    
        return (float) $$wpdb->get_var( $wpdb->prepare( "
            SELECT SUM(pm.meta_value)
            FROM {$wpdb->prefix}posts as p
            INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
            INNER JOIN {$wpdb->prefix}postmeta as pm2 ON p.ID = pm2.post_id
            WHERE p.post_type = 'shop_order'
            AND p.post_status IN ('wc-processing','wc-completed')
            AND pm.meta_key = '_order_total'
            AND pm2.meta_key = '_customer_user'
            AND pm2.meta_value = %d
        ", get_current_user_id() ) );
    }
    
    // Hide My account Orders section conditionally
    add_filter( 'woocommerce_account_menu_items', 'hide_customer_account_orders_conditionally', 100, 1 );
    function hide_customer_account_orders_conditionally( $items ) {
        if ( get_customer_purchases_total_amount() == 0 ) {
            unset( $items['orders'] );
        }
        return $items;
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.