How can i make a search box to search by custom field

The generated SQL for that query is going to look something like:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id)
INNER JOIN wp_postmeta AS mt2 ON (wp_posts.ID = mt2.post_id)
WHERE 1=1
  AND wp_posts.post_type="post"
  AND (wp_posts.post_status="publish")
  AND ((wp_postmeta.meta_key = 'culoare'
        AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%\"a\"%')
       OR (mt1.meta_key = 'culoare'
           AND CAST(mt1.meta_value AS CHAR) LIKE '%\"b\"%')
       OR (mt2.meta_key = 'culoare'
           AND CAST(mt2.meta_value AS CHAR) LIKE '%\"c\"%'))
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC LIMIT 0,10

There are three things you should notice. The first is that your query is generating an incorrect LIKE clause– '%\"c\"%'. You do not want to quote your values when you create the meta_query. Do simply:

'value'     => $culoare,

As you have it written, the query will search every row in the table but come up with nothing.

Secondly, LIKE queries, especially with wildcards– the %s– are not very efficient. The effects of that inefficiency are going to become more pronounced the larger your $wpdb->postmeta table becomes and the more conditions you try to match against.

Third, LIKE queries with an OR connector are not efficient. The query has to look at every row in the table to work out the result. Again, the effects of that inefficiency are going to become more pronounced the larger your $wpdb->postmeta table becomes and the more conditions you try to match against.

I suspect that those three problems are why this “load the cpu on my web hosting”, by which I think you mean the server slows to a crawl and times out or crashes.

There is no simple solution.

  • Try to add limiting conditions– post dates, post authors, something
    to limit the scope of the search.
  • Do you need the LIKE operator? An = or IN search would probably
    be quicker.
  • Is there any way you can cache some of this information rather than
    run a search every time? If there is, you should pursue that avenue.