-
-
Save searchwpgists/7a14a454359ed8cb6144bf2fc9f6cd89 to your computer and use it in GitHub Desktop.
Add WooCommerce Order item data to WooCommerce Orders Search in SearchWP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Add WooCommerce Order item data to WooCommerce Orders Search in SearchWP. | |
// @link https://searchwp.com/documentation/knowledge-base/search-woocommerce-orders/ | |
add_filter( 'searchwp\entry\data', function( $data, \SearchWP\Entry $entry ) { | |
// The Product data keys to index for each Order item. | |
$data_to_index = [ | |
'sku', | |
'name', | |
'slug', | |
'description', | |
'short_description', | |
'attributes', | |
]; | |
if ( | |
'post' . SEARCHWP_SEPARATOR . 'shop_order' !== $entry->get_source()->get_name() | |
|| ! function_exists( 'wc_get_order' ) | |
|| ! class_exists( 'WC_Order_Item_Product' ) | |
|| ! method_exists( 'WC_Order_Item_Product', 'get_product' ) | |
|| ! class_exists( 'WC_Product' ) | |
|| ! method_exists( 'WC_Product', 'get_data' ) | |
) { | |
return $data; | |
} | |
$order = wc_get_order( $entry->get_id() ); | |
$data['meta']['searchwp_wc_order_item_data'] = array_map( function ( $item ) use ( $data_to_index ) { | |
$product = $item->get_product(); | |
$product_data = $product->get_data(); | |
return array_filter( array_map( function( $item_key, $item_value ) use ( $data_to_index ) { | |
return in_array( $item_key, $data_to_index ) ? $item_value : ''; | |
}, array_keys( $product_data ), array_values( $product_data ) ) ); | |
}, $order->get_items() ); | |
// We need to prevent WooCommerce from excluding the order comments from our query. | |
remove_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ) ); | |
$order_comments = get_comments( array( | |
'post_id' => $order->get_id(), | |
'orderby' => 'comment_ID', | |
'order' => 'DESC', | |
'status' => 'any', | |
'type' => 'order_note', | |
) ); | |
add_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ) ); | |
$notes = wp_list_pluck( $order_comments, 'comment_content' ); | |
$data['meta']['searchwp_wc_order_notes'] = $notes; | |
return $data; | |
}, 20, 2 ); | |
// Prevent WooCommerce from limiting the results to post IDs. | |
add_filter( 'searchwp\native\args', function( $args, $query ) { | |
if ( | |
is_admin() | |
&& is_search() | |
&& isset( $_REQUEST['post_type'] ) | |
&& 'shop_order' == $_REQUEST['post_type'] | |
) { | |
$args['post__in'] = []; | |
} | |
return $args; | |
}, 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment