Himanshu Ahuja
Himanshu Ahuja

Reputation: 26

How to improve wordpress postmeta based select query?

I have created a function which get me post_id from postmeta table using meta value. Before this i was using inbuilt function from Learndash and using that my database query time was around 3.2 seconds. But after writing my own function i was able to reduce it by .4 seconds. But i still think it can be optimized more because Query Monitor plugin is marking my query also as slow.

screenshot:

Query Monitor Slow queries

I am trying to improve the speed of below code and I have tried all of possible workaround and techniques.

This is the code:

public function ntml_question_pid_by_proid($meta_value)
        {
            global $wpdb;

            $tbl = $wpdb->prefix . 'postmeta';

            $prepare_guery = $wpdb->prepare("
SELECT post_id 
  FROM $tbl 
 where meta_key = 'question_pro_id' 
   and meta_value like '%s'
", $meta_value);

            $get_values = $wpdb->get_col($prepare_guery);

            if (is_array($get_values) && count($get_values) > 0) {
                return $get_values[0];
            } else {
                return false;
            }
        }

Is there a workaround that will improve page speed by minimum of 2 seconds?

We already have memcache too.

Upvotes: 0

Views: 1207

Answers (1)

O. Jones
O. Jones

Reputation: 108796

Stale question, I know.

Try adding columns to postmeta's meta_key index index.

ALTER TABLE wp_postmeta 
  DROP INDEX meta_key,
  ADD INDEX (meta_key(32), meta_value(32), post_id);

Or use the WP Index MySQL For Speed plugin. It updates quite a few indexes.

Upvotes: 1

Related Questions