Search WooCommerce order item meta

/**
 * Searches WooCommerce order item meta.
 *
 * @see https://wpcodebook.com/woocommerce-search-order-item-meta/
 *
 * @return array Order IDs.
 */
function wpcodebook_order_item_meta_search( $meta_key, $meta_value ) {
	global $wpdb;
	$query = "SELECT DISTINCT items.order_id
		FROM {$wpdb->prefix}woocommerce_order_items AS items
		LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS itemmeta ON items.order_item_id = itemmeta.order_item_id
		WHERE meta_key LIKE '%s'
		AND meta_value = %s";
	$order_ids = $wpdb->get_col( $wpdb->prepare( $query, $meta_key, $meta_value ) );
	return $order_ids;
}

Leave a Comment