Get WooCommerce Order Notes

User
How to get woocommerce order notes added by admin by per user order
Assistant
You can retrieve WooCommerce order notes added by an admin for a specific user's order using the `wc_get_order_notes()` function. Here’s how you can do it:

### 1. **Get Order Notes for a Specific Order**
If you have an order ID, you can fetch the order notes like this:

$order_id = 123; // Replace with the actual order ID
$notes = wc_get_order_notes([
    'order_id' => $order_id,
    'type'     => 'internal', // Fetch only admin/internal notes
]);

foreach ($notes as $note) {
    echo '<p>' . esc_html($note->content) . '</p>';
}

### 2. **Get Order Notes for All Orders of a User**
If you want to fetch notes for all orders of a specific user, you can do this:

$user_id = get_current_user_id(); // Replace with the actual user ID if needed
$customer_orders = wc_get_orders([
    'customer_id' => $user_id,
    'status'      => 'any', // Fetch orders with any status
]);

foreach ($customer_orders as $order) {
    $order_id = $order->get_id();
    $notes = wc_get_order_notes([
        'order_id' => $order_id,
        'type'     => 'internal',
    ]);

    echo '<h3>Order ID: ' . $order_id . '</h3>';
    foreach ($notes as $note) {
        echo '<p>' . esc_html($note->content) . '</p>';
    }
}

### Explanation:
– `wc_get_order_notes()` retrieves order notes for a specific order.
– `'type' => 'internal'` ensures that only admin-added notes are fetched (customer notes are of type `customer`).
– `wc_get_orders()` retrieves all orders for a specific user.

Let me know if you need modifications based on your setup!

User
Each unique user and their order count then click on count will show all notes
Assistant
You can achieve this by displaying a list of unique users with their order count, and when clicking on the order count, it will show all order notes for that user using AJAX.

### **1. Create a Shortcode to Display Users with Order Count**
Add this to your theme’s `functions.php` or a custom plugin:

function get_woocommerce_users_with_orders() {
    $users = get_users([
        'role__in' => ['customer', 'subscriber'], // Get only WooCommerce customers
        'fields'   => ['ID', 'display_name', 'user_email'],
    ]);

    ob_start();
    ?>
    <table>
        <tr>
            <th>User Name</th>
            <th>Email</th>
            <th>Order Count</th>
        </tr>
        <?php
        foreach ($users as $user) {
            $user_id = $user->ID;
            $orders = wc_get_orders([
                'customer_id' => $user_id,
                'status'      => 'any',
                'return'      => 'ids', // Only fetch order IDs for performance
            ]);

            $order_count = count($orders);

            if ($order_count > 0) {
                echo "<tr>
                        <td>{$user->display_name}</td>
                        <td>{$user->user_email}</td>
                        <td><a href='#' class='show-order-notes' data-userid='{$user_id}'>{$order_count}</a></td>
                      </tr>";
            }
        }
        ?>
    </table>
    <div id="order-notes-container"></div>

    <script>
    jQuery(document).ready(function($) {
        $(".show-order-notes").on("click", function(e) {
            e.preventDefault();
            var userId = $(this).data("userid");

            $.ajax({
                url: "<?php echo admin_url('admin-ajax.php'); ?>",
                type: "POST",
                data: {
                    action: "fetch_order_notes",
                    user_id: userId
                },
                beforeSend: function() {
                    $("#order-notes-container").html("<p>Loading...</p>");
                },
                success: function(response) {
                    $("#order-notes-container").html(response);
                }
            });
        });
    });
    </script>
    <?php
    return ob_get_clean();
}
add_shortcode('user_order_list', 'get_woocommerce_users_with_orders');

### **2. Create an AJAX Handler to Fetch Order Notes**
Add this below the previous function in `functions.php`:

function fetch_order_notes() {
    if (!isset($_POST['user_id'])) {
        wp_send_json_error('User ID missing');
    }

    $user_id = intval($_POST['user_id']);
    $customer_orders = wc_get_orders([
        'customer_id' => $user_id,
        'status'      => 'any',
    ]);

    if (empty($customer_orders)) {
        wp_send_json_success('<p>No orders found for this user.</p>');
    }

    ob_start();
    echo "<h3>Order Notes</h3>";

    foreach ($customer_orders as $order) {
        $order_id = $order->get_id();
        $notes = wc_get_order_notes([
            'order_id' => $order_id,
            'type'     => 'internal',
        ]);

        echo "<h4>Order ID: $order_id</h4>";
        if (!empty($notes)) {
            foreach ($notes as $note) {
                echo "<p>" . esc_html($note->content) . " (Added on: " . esc_html($note->date_created) . ")</p>";
            }
        } else {
            echo "<p>No notes for this order.</p>";
        }
    }

    wp_send_json_success(ob_get_clean());
}
add_action('wp_ajax_fetch_order_notes', 'fetch_order_notes');
add_action('wp_ajax_nopriv_fetch_order_notes', 'fetch_order_notes'); // Allow non-logged-in users if needed

### **How It Works**
1. The shortcode `[user_order_list]` will list all users who have placed orders.
2. The order count is clickable. When clicked, it triggers an AJAX request to fetch order notes.
3. The AJAX function retrieves all order notes for that user’s orders and displays them in `#order-notes-container`.

### **Usage**
– Add the shortcode `[user_order_list]` to any page or post.
– Clicking on an order count will dynamically load the order notes for that user.

Let me know if you need any improvements!

Assistant
To create a functionality that displays each unique user with their order count, and allows you to click on the count to view all order notes, you can follow these steps:

### Step 1: Retrieve Unique Users with Order Counts

First, you need to get the unique users who have placed orders and count their orders.

// Get all customer orders
$customer_orders = wc_get_orders([
    'limit' => -1, // Get all orders
]);

// Array to store user IDs and their order counts
$user_order_counts = [];

// Loop through each order and count orders per user
foreach ($customer_orders as $order) {
    $user_id = $order->get_user_id();
    if ($user_id) {
        if (!isset($user_order_counts[$user_id])) {
            $user_order_counts[$user_id] = 0;
        }
        $user_order_counts[$user_id]++;
    }
}

### Step 2: Display the Users and Their Order Counts

Next, display the users and their respective order counts in a list. When you click on the count, it will trigger a function to show the notes.

echo '<ul>';
foreach ($user_order_counts as $user_id => $count) {
    $user_info = get_userdata($user_id);
    echo '<li>';
    echo esc_html($user_info->display_name) . ' (' . esc_html($count) . ')';
    echo ' <a href="#" class="view-notes" data-user-id="' . esc_attr($user_id) . '">View Notes</a>';
    echo '</li>';
}
echo '</ul>';

### Step 3: Handle Click Events with JavaScript

You'll need JavaScript to handle the click event on the "View Notes" link and fetch the order notes for that user.

<script>
document.querySelectorAll('.view-notes').forEach(function(link) {
    link.addEventListener('click', function(e) {
        e.preventDefault();
        
        const userId = this.getAttribute('data-user-id');
        
        fetch('/path-to-your-endpoint?user_id=' + userId) // Update the endpoint accordingly
            .then(response => response.json())
            .then(data => {
                // Handle displaying the notes (data contains order notes)
                let notesHtml = '<h3>Order Notes for User ' + userId + '</h3>';
                data.forEach(note => {
                    notesHtml += '<p>' + note.content + '</p>';
                });
                // Assuming you have a div to display notes
                document.getElementById('order-notes-container').innerHTML = notesHtml;
            });
    });
});
</script>

### Step 4: Create an Endpoint to Fetch Notes

You need a PHP function that will handle the AJAX request to fetch order notes for a specific user.

add_action('wp_ajax_get_user_order_notes', 'get_user_order_notes');
add_action('wp_ajax_nopriv_get_user_order_notes', 'get_user_order_notes'); // If you want to allow non-logged-in users

function get_user_order_notes() {
    if (!isset($_GET['user_id'])) {
        wp_send_json_error('User ID not provided.');
        return;
    }

    $user_id = intval($_GET['user_id']);
    $orders = wc_get_orders([
        'customer_id' => $user_id,
        'status'      => 'any',
        'limit'       => -1, // Get all orders for this user
    ]);

    $all_notes = [];
    foreach ($orders as $order) {
        $order_id = $order->get_id();
        $notes = wc_get_order_notes([
            'order_id' => $order_id,
            'type'     => 'internal',
        ]);

        foreach ($notes as $note) {
            $all_notes[] = [
                'content' => esc_html($note->content),
            ];
        }
    }

    wp_send_json_success($all_notes);
}

### Step 5: Display Notes Container

Add a container in your HTML to display the order notes when the user clicks on the count.

<div id="order-notes-container"></div>

### Summary

1. You retrieve unique users and their order counts.
2. Each count links to a JavaScript function that fetches order notes.
3. You create a PHP function to handle AJAX requests for fetching notes.

Make sure to replace `/path-to-your-endpoint` with the actual endpoint where your AJAX request is routed. Let me know if you need any further adjustments!

Leave a Comment

Your email address will not be published. Required fields are marked *