Skip to content

Instantly share code, notes, and snippets.

@bahiirwa
Forked from devinsays/OrdersList.php
Created June 3, 2022 06:26
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 bahiirwa/10355579564b2e398b6b42956c267687 to your computer and use it in GitHub Desktop.
Save bahiirwa/10355579564b2e398b6b42956c267687 to your computer and use it in GitHub Desktop.
Speeds up the loading of /wp-admin/edit.php?post_type=shop_order and /wp-admin/edit.php?post_type=subscription.
<?php
namespace UniversalYums\Admin\Performance;
class OrdersList {
/**
* The single instance of the class.
*/
protected static $instance;
/**
* Instance.
*/
public static function instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
public function __construct() {
add_action( 'posts_where', [ $this, 'change_where_clause_for_admin_order_list' ], 99, 2 );
}
/**
* Check if we are on the admin orders or subscriptions "All" page.
*
* @return bool
*/
public function is_admin_all_list_page() {
if ( ! is_admin() ) {
return false;
}
if ( wp_doing_ajax() ) {
return false;
}
$request = wp_unslash( $_SERVER['REQUEST_URI'] );
if ( strpos( $request, '/wp-admin/edit.php' ) === false ) {
return false;
}
if ( ! isset( $_GET['post_type'] ) ) {
return false;
}
if ( isset( $_GET['post_status'] ) ) {
return false;
}
if ( 'shop_order' === $_GET['post_type'] || 'shop_subscription' === $_GET['post_type'] ) {
return true;
}
return false;
}
/**
* If we are on the admin Orders or Subscriptions 'All' page, simplify the WHERE clause by removing post_status search.
*
* Potential Issue:
* We might see orders that don't have a WC status. But, maybe that's also a good thing?
*
* @param $where
* @param $wp_query
* @return mixed|string
*/
public function change_where_clause_for_admin_order_list( $where, $wp_query ) {
global $wpdb;
if ( ! $wp_query->is_main_query() ) {
return $where;
}
if ( ! $this->is_admin_all_list_page() ) {
return $where;
}
if ( 'shop_order' === $_GET['post_type'] ) {
$where = "AND $wpdb->posts.post_type = 'shop_order'";
}
if ( 'shop_subscription' === $_GET['post_type'] ) {
$where = "AND $wpdb->posts.post_type = 'shop_subscription'";
}
return $where;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment