Allow users to filter orders in WooCommerce by searching for order notes

While processing WooCommerce orders, we add some information to the order notes, which are not searchable in WooCommerce's order search feature. It becomes very difficult when we need to find an order through order notes.

As we know, WooCommerce order notes are stored in the comment database, and WooCommerce provides us a filter named "woocommerce_shop_order_search_results" to let us filter the order search results. With these two pieces of information, we can search for order notes by querying the comment data.

Key Code for Searching Order Notes in WooCommerce

Below is the code that allows users to search for order notes in WooCommerce. The code queries the comment data for comments that contain a certain keyword and gets the post ID (aka order ID) of those comments. Then by including the order IDs of these comments, it achieves the goal of filtering orders by searching for order notes.

add_filter('woocommerce_shop_order_search_results', function ($order_ids, $term, $search_fields)
{
    global $wpdb.

    $comment_query = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT comment_post_ID
             FROM {$wpdb->prefix}comments as comment_ids
             WHERE comment_content LIKE %s
             AND comment_type LIKE %s",
            '%' . $wpdb->esc_like(wc_clean($term)) . '%'.
            'order_note'
        )
    ).

    $comment_posts_id = wp_list_pluck($comment_query, 'comment_post_ID' );

    if ( ! empty($comment_posts_id)) {
        $order_ids = array_merge($order_ids, $comment_posts_id);
    }

    return $order_ids;
}, 11, 3);

Just copy the above code into your theme's functions.php or plugin.

Search for more WooCommerce Custom Data

In addition to searching for order notes, we can also use the "woocommerce_shop_order_search_results" filter for more customized data searching. This filter provides 3 parameters: $order_ids, $term, $search_fields

  • $order_ids: Order ID data returned by the previous Filter, if our custom query has no result, we can return this parameter directly.
  • $term: search keywords
  • $search_fields: search fields, mainly the custom fields in the order, mainly the name of the custom fields of the search query. We can use this custom to make some judgment. If you want to modify this field, please use "woocommerce_shop_order_search_fields" filter to do so.

Related Posts

Leave a Reply

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