Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

I have a large DB of posts and I want to search via meta data. One of WordPress

  • SOLVED

I have a large DB of posts and I want to search via meta data. One of the items is exact as an example unit 80 vs say unit 90, the other I want to search as they type and get a partial match eg: if its was a unit number 2903 and I type 29 I would get any results starting with 29 so 290, 291, 298, etc. but also 2901, 2903 as an example.

Answers (1)

2020-01-08

John Cotton answers:

It's not a very efficient way to search, particularly if you have a large database, but this will return you the results (eventually!)


$my_key = 'units';
$number = 29;

$query = new WP_Query(
array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => $my_key,
'value' => "^{$number}",
'compare' => 'REGEXP',
)
)
));


John Cotton comments:

If you data runs into tens of thousands of rows, or more, I would consider creating a custom table, with two fields - the post id and the unit number (with the latter as an INT value rather than the string type that meta_value is).

You could then do a SQL join to get your post data and any other meta table. Add a decent index to the custom table and you should get good performance even with 100's of thousands of rows.