/** * Cache the heavy Bible SuperSearch shortcode scanner query */ add_filter('query', 'cache_bible_supersearch_scan_query'); function cache_bible_supersearch_scan_query($query) { // Target the exact slow query identified in your slow.log if (strpos($query, "post_content LIKE '%[biblesupersearch]%'") !== false && strpos($query, "wptv2i_posts") !== false) { $transient_name = 'bss_scanned_posts_cache'; $cached_result = get_transient($transient_name); // If we have a cached version, return a dummy query or empty string if it's safe, // but better yet, short-circuit the execution by returning a modified query that uses the cached IDs. if ($cached_result !== false) { // Force the query to instantly look up only the specific known post IDs instead of scanning 36,000+ rows if (!empty($cached_result)) { $ids = implode(',', array_map('intval', $cached_result)); return "SELECT ID, post_title, post_type, post_content FROM `wptv2i_posts` WHERE ID IN ($ids);"; } else { // If no posts have it, return a query that breaks immediately and safely return "SELECT ID, post_title, post_type, post_content FROM `wptv2i_posts` WHERE ID = 0;"; } } // If not cached, let the query run, intercept the data later, or run it once manually to cache it global $wpdb; // Temporarily remove the filter to prevent an infinite loop during our manual fetch remove_filter('query', 'cache_bible_supersearch_scan_query'); $results = $wpdb->get_col($query); // Get the IDs matching the query // Re-add the filter add_filter('query', 'cache_bible_supersearch_scan_query'); // Store the result IDs for 24 hours (86400 seconds) set_transient($transient_name, $results, DAY_IN_SECONDS); // Fallback to the original query execution for this first run return $query; } return $query; } /** * Clear the cache whenever a post or page is saved/updated so things don't break */ add_action('save_post', 'clear_bible_supersearch_scan_cache'); function clear_bible_supersearch_scan_cache() { delete_transient('bss_scanned_posts_cache'); }