Skip to content

Instantly share code, notes, and snippets.

@DanielMarklund
Last active December 6, 2023 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanielMarklund/6849386e6e6ad417a4ada224f930ec72 to your computer and use it in GitHub Desktop.
Save DanielMarklund/6849386e6e6ad417a4ada224f930ec72 to your computer and use it in GitHub Desktop.
Limit order search fields in WooCommerce for speed optimization
<?php
/**
* Class Limit_Order_Search_Fields
*
* Limits WooCommerce order searches to email, phone, order ID, shipping & billing address indexes and name
* for admins and shop managers to limit optimize speed in order search.
*
* Installation: Place this file in the mu-plugins folder.
* If you do not have a mu-plugins folder you can create one in the wp-content folder.
* No activation is needed and the plugin will work immediately.
*
* Author: Daniel Leis
* Version: 1.0
*/
class Limit_Order_Search_Fields {
/**
* Constructor for the Limit_Search class.
*
* This constructor checks if the current user has the capability to manage options or manage WooCommerce,
* and if the current page is the admin page for shop orders in WooCommerce.
* If the conditions are met, it adds a filter to limit the search fields for shop orders in WooCommerce.
*/
public function __construct() {
if (
(current_user_can('manage_options') || current_user_can('manage_woocommerce'))
&& (is_admin() && class_exists('woocommerce') && isset($_GET['post_type']) && $_GET['post_type'] === 'shop_order')
) {
add_filter('woocommerce_shop_order_search_fields', array($this, 'limit_order_search_fields'));
}
}
/**
* Limits the search fields for order search.
*
* This function is used to limit the search fields for order search in WordPress.
* It sets the specific fields that will be used for searching orders.
*
* @param array $search_fields The array of search fields.
* @return array The modified array of search fields.
*/
public function limit_order_search_fields(array $search_fields) {
$search_fields = array(
'_billing_address_index',
'_shipping_address_index',
'_billing_first_name',
'_billing_last_name',
'_billing_email',
'_billing_phone',
'ID'
);
return $search_fields;
}
}
/**
* Adds an action to the 'init' hook to initialize the Limit_Order_Search_Fields class.
* This is needed to get access to current user capabilities, current page and post type functions.
*/
add_action('init', function(){
new Limit_Order_Search_Fields();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment