Skip to content

Instantly share code, notes, and snippets.

@brettshumaker
Created August 31, 2020 13:56
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 brettshumaker/0aabb70e67023cb473b5dbfe00e75251 to your computer and use it in GitHub Desktop.
Save brettshumaker/0aabb70e67023cb473b5dbfe00e75251 to your computer and use it in GitHub Desktop.
Filters `query` to fix slow queries during `post_exists()`
<?php
/**
* This adds `post_type` and `post_status` to the query that happens during `post_exists()` so it can utilize the `type_status_date` index on `wp_posts`.
* Hooked on `query` during `wp_import_post_data_raw` and removed during `wp_import_existing_post`.
*
* Modifies a query like this from `post_exists()`:
* SELECT ID FROM wp_posts WHERE 1=1 AND post_date = '2020-07-01 09:30:00' AND post_title = 'Some Post Title'
*
* To this:
* SELECT ID FROM wp_posts WHERE 1=1 AND post_date = '2020-07-01 09:30:00' AND post_title = 'Some Post Title' AND post_type = 'post' AND post_status = 'publish'
*
* @param string $query
* @return string
*/
function wpcomvip_import_query_filter ( $query ) {
global $wp_import_post_data_raw;
if ( is_null( $wp_import_post_data_raw ) || strpos( $query, 'SHOW FULL COLUMNS' ) !== false ) {
return $query;
}
$modified_query_parts = array();
if ( isset( $wp_import_post_data_raw['post_type'] ) ) {
$modified_query_parts[] = "AND post_type = '" . $wp_import_post_data_raw['post_type'] . "'";
}
if ( isset( $wp_import_post_data_raw['status'] ) ) {
$modified_query_parts[] = "AND post_status = '" . $wp_import_post_data_raw['status'] . "'";
}
$modified_query = $query . ' ' . implode( ' ', $modified_query_parts );
$wp_import_post_data_raw = null;
return $modified_query;
}
// Add our `query` filter after we get the post data we're trying to import.
add_filter( 'wp_import_post_data_raw', function( $post ) {
// Set up global data to use in the `query` filter.
global $wp_import_post_data_raw;
$wp_import_post_data_raw = $post;
// Add the `query` filter if it hasn't already been added AND the `post_type` is not `nav_menu_item`.
if ( false === has_filter( 'query', 'wpcomvip_import_query_filter' ) && 'nav_menu_item' !== $post['post_type'] ) {
add_filter( 'query', 'wpcomvip_import_query_filter' );
}
// return the unmodified data
return $post;
} );
// Remove our `query` filter after we've done `post_exists()`.
add_filter( 'wp_import_existing_post', function( $post ) {
// Remove the `query` filter.
remove_filter( 'query', 'wpcomvip_import_query_filter' );
// return the unmodified data
return $post;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment