Currently, when I load a search or result page, it queries the wp_postmeta table which is leading to the page taking ages to load. I realise this is a result of this table being huge (70k rows), and because of how much data is loaded into the cache.

Is there a way to stop update_post_caches from being called when these pages are loaded, and then send custom (and more efficient) queries to the database once the template has been loaded?

enter image description here

1 Answer 1

add_filter('pre_get_posts', 'customize_query');
function customize_query($query) {
    if($query->is_main_query() && ($query->is_search() || $query->is_archive()) {
        $query->set('update_post_meta_cache', false);
        $query->set('update_post_term_cache', false);

Then wordpress will make 2 less queries for those pages & then you can use the $wpdb object to write custom queries.

  • +1 Good answer! I just want to add that the reason we call is_main_query first is so as not to have effect on other things like nav menu and comment queries. Its not always clear why we do that for those that wish to know.
    – Adam
    Oct 22, 2012 at 11:05
  • It doesn't affect comment queries anyway, but yes for nav menu & also if you create WP_Query object in your template files/widgets etc. Oct 22, 2012 at 11:23
  • Comment widget is what I should have said, very good point about WP_Query objects too.
    – Adam
    Oct 22, 2012 at 11:28
  • 1
    nope, anything related to comments has a separate filter pre_get_comments Oct 22, 2012 at 11:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.