Arrange charges by title in WooCommerce orders and email alerts

Is there a way to sort fees by name instead of the default sorting by price in WooCommerce orders?

I was able to successfully sort fees by name on the cart and checkout pages using the code provided in the answer located at Reordering multiple fees differently in Woocommerce cart and checkout pages. However, I am facing issues with getting this sorting to work on order confirmation emails.

Your assistance is greatly appreciated.

Answer №1

Updated

If you want to organize fees by name on customer orders and email notifications, the following code snippet will help you achieve that:

// Custom function that sorts displayed fees by name on order items
function wc_get_sorted_order_item_totals_fee_rows( &$total_rows, $tax_display, $order ) {
    $fees = $order->get_fees();

    if ( $fees ) {
        $fee_names = []; // initializing

        // First Loop
        foreach ( $fees as $fee_id => $fee ) {
            $fee_names[$fee_id] = $fee->get_name();
        }
        asort($fee_names); // Sorting by name

        // 2nd Loop
        foreach ( $fee_names as $fee_id => $fee_name ) {
            $fee = $fees[$fee_id];

            if ( apply_filters( 'woocommerce_get_order_item_totals_excl_free_fees', empty( $fee['line_total'] ) && empty( $fee['line_tax'] ), $fee_id ) ) {
                continue;
            }

            $total_rows[ 'fee_' . $fee->get_id() ] = array(
                'label' => $fee->get_name() . ':',
                'value' => wc_price( 'excl' === $tax_display ? $fee->get_total() : $fee->get_total() + $fee->get_total_tax(), array( 'currency' => $order->get_currency() ) ),
            );
        }
    }
}

// Display sorted fees by name everywhere on orders and emails
add_filter( 'woocommerce_get_order_item_totals', 'display_date_custom_field_value_on_order_item_totals', 10, 3 );
function display_date_custom_field_value_on_order_item_totals( $total_rows, $order, $tax_display ){
    // Initializing variables
    $new_total_rows = $item_fees = [];

    // 1st Loop - Check for fees
    foreach ( $total_rows as $key => $values ) {
        if( strpos($key, 'fee_') !== false ) {
            $item_fees[] = $key;
        }
    }

    if( count($item_fees) > 1 ) {
        // 2nd Loop - Remove item fees total lines
        foreach ( $item_fees as $key ) {
            unset($total_rows[$key]);
        }

        $key_start = isset($total_rows['shipping']) ? 'shipping' : ( isset($total_rows['discount']) ? 'discount' : 'cart_subtotal' );

        // 3rd Loop - loop through order total rows
        foreach( $total_rows as $key => $values ) {
            $new_total_rows[$key] = $values;

            // Re-inserting sorted fees
            if( $key === $key_start ) {
                wc_get_sorted_order_item_totals_fee_rows( $new_total_rows, $tax_display, $order );
            }
        }
        return $new_total_rows;
    }
    return $total_rows;
}

This code should be placed in the functions.php file of your active child theme or active theme. It has been tested and confirmed to work.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Shared class attribute on a PHP object

Does PHP allow for a class to store an object of the same class? Is there a method to achieve this behavior in PHP since it doesn't support pointers like C++? ...

Transmit an array of JavaScript objects using Email

Within the code layout provided with this post, I have executed various operations in JavaScript which resulted in an array of objects named MyObjects. Each object within MyObjects contains properties for Name and Phone, structured as follows: MyObject ...

"Can someone show me the process of extracting data from a URL using preg_match

Here is a link to my website: <a href="http://example.com/post/12345">sample_post</a> I am trying to extract the URL using preg_match_all(); http://example.com/post/12345 Any assistance would be appreciated. ...

Which CMS is better for creating a social network: Drupal or WordPress?

Creating a community for web-comic artists to synchronize their websites is my current project. The dilemma I am facing now is deciding between using Drupal or Wordpress as the CMS. Although Drupal is renowned for its Social Networking capabilities, I fo ...

Identify when an ajax request is completed in order to trigger a subsequent ajax request

Within my project, I am faced with a challenge involving select option groups that dynamically load ajax data based on previous selections. The issue arises when I attempt to replicate this functionality for another select option group. Here is the scenar ...

Loading dynamic CSS on WordPress frontend only

I am facing an issue with the dynamic css file in my WordPress theme that is loaded using Ajax. The problem is that it also loads this dynamic css file for the backend. Can someone help me modify my code so that it only loads the dynamic css file for the f ...

Using AJAX to remove data from a database

My PHP code snippet is displayed below: AjaxServer.php include '../include/connection.php'; // Check for the prediction if(isset($_POST["delete_me"]) && $_POST["delete_me"]=="true"){ $id = $_POST["id"]; $table = $_POST["table"]; ...

Why am I receiving a "definition varies" notification even though they are identical?

Within Laravel, I have a User class that extends Authenticatable and implements a trait known as Activable: class User extends Authenticable { use Activable; protected $is_active_column = 'is_active'; } trait Activable { /** ...

The WHERE NOT IN statement doesn't function in PHP, but it is effective in SQL queries

Trying to extract specific values from one table that are not present in another table poses a challenge. This is the SQL query used: SELECT `u882219588_data`.`user`.`user_name`, `u882219588_data`.`user`.`email`, `u882219588_data`.`user`.`name` FR ...

Debugging an Asterisk AGI file in PHP

Looking for help debugging the AGI script (a2billing.php) in Asterisk. I've been successful when remotely debugging PHP CLI from the Linux console, but it doesn't seem to work when running within Asterisk. Any suggestions on how to properly debu ...

What is the best way to determine if a query should be executed based on a value stored in $_SESSION?

To ensure that user input is stored in the database, I want to check if the user's $_SESSION variable has a non-null value before proceeding. This is the current code snippet I am using: $verifiedd = $_SESSSION['verified']; if (is_null($ve ...

Establishing a connection using stream_socket_client that includes the ability to set

Looking at this block of PHP code: $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx); The number '60' in the code represents a timeout for the connection establishm ...

While working with ajax form submission in CodeIgniter, I encountered an issue where I did not receive the expected value in the

For my project, I am using PHP Codeigniter and submitting a form through an Ajax call. However, I am facing an issue where I am not receiving the expected value in the success message. Below is the code snippet: Ajax Call: function addLocation(){ va ...

What is the best way to have PHP execute numerous calls from an array to a script, ensuring that each function completes before proceeding?

In my script, I have an array of properties that includes a list of properties along with their corresponding .ics locations. When I run the script manually for each element in the array individually, it works perfectly. However, when I attempt to loop thr ...

Cross-origin resource sharing (CORS): In PHP, the response to the preflight request is not successfully passing. I am permitting

With the abundance of CORS posts already out there, I find myself adding to them in search of a solution. My dilemma involves building an angular 4 application that interacts with my php api. Locally, everything works seamlessly. However, once I upload the ...

Unsure about the approach to handle this PHP/JSON object in Javascript/jQuery

From my understanding, I have generated a JSON object using PHP's json_encode function and displayed it using echo. As a result, I can directly access this object in JavaScript as an object. Here is an example: .done(function(response) { var ...

transferring a parameter in PHP

I am just starting out with PHP (with some experience in Java) However, I'm struggling to pass a variable as an argument. Here's my code snippet where I define the URL in a variable called "url" and try to use it to make an API call. The issue ...

The jquery error NS_ERROR_XPC_BAD_CONVERT_JS is causing issues on Google Chrome while working fine on Firefox

Currently, I am utilizing jQuery to dynamically add fields to a form. These are considered "repeatable" fields since users can click an "add more" button. Here is the code snippet: $(".add-attacker-scores").click(function() { count = count + 1; ...

Loading data onto a different JQGrid when a row is selected using OnSelectRow

For the past few days, I have been struggling with a perplexing issue. Here's a brief overview of the problem - I'm working with JqGrid 4.2.0 (the latest version available at the time of writing) and have two grids on a single page. The left grid ...

Guide on utilizing ffmpeg in conjunction with PHP for file compression and uploading

Hello everyone, I have successfully installed ffmpeg on my local computer and now I'm looking to learn how to use it for uploading files via PHP to the server. My goal is to convert all user-uploaded files to SWF format. Additionally, I've increa ...