0
0
Wordpressframework~5 mins

Meta queries for filtering in Wordpress

Choose your learning style9 modes available
Introduction

Meta queries help you find posts or items based on extra information stored with them. This lets you filter content easily.

You want to show posts with a specific custom field value.
You need to filter products by price or color stored as metadata.
You want to find events happening on a certain date saved in meta.
You want to combine multiple meta conditions to narrow results.
You want to exclude posts with certain meta values.
Syntax
Wordpress
'meta_query' => [
  [
    'key' => 'meta_key_name',
    'value' => 'value_to_compare',
    'compare' => '=',
    'type' => 'CHAR'
  ],
  // More meta query arrays can be added
]

key is the meta field name you want to filter by.

value is what you want to match or compare.

Examples
Find products where the 'color' meta field is exactly 'blue'.
Wordpress
$args = [
  'post_type' => 'product',
  'meta_query' => [
    [
      'key' => 'color',
      'value' => 'blue',
      'compare' => '='
    ]
  ]
];
Find posts with 'price' meta between 10 and 50.
Wordpress
$args = [
  'meta_query' => [
    [
      'key' => 'price',
      'value' => [10, 50],
      'compare' => 'BETWEEN',
      'type' => 'NUMERIC'
    ]
  ]
];
Find posts where 'color' is 'red' AND 'size' is 'large'.
Wordpress
$args = [
  'meta_query' => [
    'relation' => 'AND',
    [
      'key' => 'color',
      'value' => 'red',
      'compare' => '='
    ],
    [
      'key' => 'size',
      'value' => 'large',
      'compare' => '='
    ]
  ]
];
Sample Program

This code finds all 'product' posts where the meta field 'color' equals 'green'. It prints the titles of those products or a message if none are found.

Wordpress
<?php
$args = [
  'post_type' => 'product',
  'meta_query' => [
    [
      'key' => 'color',
      'value' => 'green',
      'compare' => '='
    ]
  ]
];
$query = new WP_Query($args);

if ($query->have_posts()) {
  while ($query->have_posts()) {
    $query->the_post();
    echo get_the_title() . "\n";
  }
} else {
  echo "No products found with color green.\n";
}
wp_reset_postdata();
OutputSuccess
Important Notes

Always set the type in meta queries when comparing numbers or dates to avoid wrong results.

You can combine multiple meta queries using relation with 'AND' or 'OR'.

Use wp_reset_postdata() after custom queries to restore global post data.

Summary

Meta queries filter posts by custom field values.

You can compare exact values, ranges, or multiple conditions.

They help create dynamic and precise content filters in WordPress.