wphats

WordPress Meta Query Examples for Custom Post Type

WordPress Meta Query Examples for Custom Post Type

Meta Field that we can call as ‘Custom Field’ is well known to everybody. In WordPress, we use certainly custom field/fields for our necessity of requirements. But in terms of getting output, sometimes we face bit problem to make query for that. So in this tutorial i am going to show some query for Meta Key/Value. Before starting the query please have a look for the parameters:

  •      meta_key (string) – Custom field key.
  •     meta_value (string) – Custom field value.
  •     meta_value_num (number) – Custom field value.
  •     meta_compare (string) – Operator to test the ‘meta_value’. Possible values are ‘=’, ‘!=’, ‘>’, ‘>=’, ‘<‘, ‘<=’, ‘LIKE’, ‘NOT LIKE’, ‘IN’, ‘NOT IN’, ‘BETWEEN’, ‘NOT BETWEEN’, ‘NOT EXISTS’, ‘REGEXP’, ‘NOT REGEXP’ or ‘RLIKE’. Default value is ‘=’.
  •     meta_query (array) – Custom field parameters (available with Version 3.1).
    relation (string) – The logical relationship between each inner meta_query array when there is more than one. Possible values are ‘AND’, ‘OR’. Do not use with a single inner meta_query array.

In very simple way now we can write the query to show posts associated with a certain custom field. Following example displays posts from the ‘product’ post type that have meta key ‘color’ with value ‘blue’, using 'meta_query':

The above example we can follow in some other ways also in order to fulfill our requirements.

Display posts where the custom field key is ‘color’, regardless of the custom field value:

Display posts where the custom field value is ‘blue’, regardless of the custom field key:

Display posts where the custom field key is ‘color’ and the custom field value is ‘blue’:

Display posts where the custom field key is ‘color’ and the custom field value IS NOT ‘blue’:

Display ‘product'(s) where the custom field key is ‘price’ and the custom field value that is LESS THAN OR EQUAL TO 22.
By using the ‘meta_value’ parameter the value 99 will be considered greater than 100 as the data are stored as ‘strings’, not ‘numbers’. For number comparison use ‘meta_value_num’.

Display posts from several custom field:

Display posts that have meta key ‘color’ NOT LIKE value ‘blue’ OR meta key ‘price’ with values BETWEEN 20 and 100:

I hope from the above examples of meta query you will understand the basic query order for custom fields. Still if you have any issues or question feel free to drop message below, we will answer your question shortly.

Thanks.

This post has already been read 3655 times!

Mehedi Hasan

Cool WordPress Developer having much agile experience to develop any kind of WordPress sites & plugins. Also good in troubleshooting, fixing & making any kind of tweaks for WP site.

More Posts

POSTED ON: Wordpress Basics, Wordpress Development
TAGGED : , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *