Skip to content
Advertisement

WooCommerce sql query to find products with a specific meta key and meta value

I am trying to get products with a custom field with value condition from DB.

Custom field is named: “_filtered_product”.
I want to get products only with value = 1

This is SQL query I have written.

Advertisement

Answer

Not sure why you want to write your own sql query for this simple task, while you could use wp_query!

That being said, you could use the following snippet to get all products with a specific meta key and meta value:

Which will output this:

Note:

  • The query above, will retrieve all of the data for a product. I just used ID and title to give you an example.
  • If your $meta_value is string, then you’re all set, meaning I’ve written the query, assuming that you meta value is string. However, if it’s NOT, then use this {$meta_value} instead of '{$meta_value}'.
  • I’ve used global $wpdb and took advantage of its properties and methods.
  • Instead of hard-coding your database tables prefix which by default would be wp_, I’ve used {$wpdb->prefix}.
  • I’ve also used $wpdb->prepare statement to secure the sql statement.
  • Also, I’ve used ARRAY_A as the second argument in the $wpdb->get_results function, to get the data as an associative array!
  • Also, be aware that this query is ordered by date, descending, meaning recent products will get outputted first!

Performing the same query using wp_query:

This answer has been fully tested on woocommerce 5.x+ and works fine!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement