How to Query by Custom Field in WordPress Easily
To query posts by a custom field in WordPress, use the
meta_query parameter inside WP_Query. Specify the custom field key and value to filter posts that match your criteria.Syntax
The meta_query parameter is an array of arrays where each inner array defines a condition on a custom field. You specify the key (custom field name), value (what you want to match), and compare (how to compare, e.g., '=', 'LIKE').
This lets WordPress filter posts based on custom field values.
php
new WP_Query([ 'meta_query' => [ [ 'key' => 'custom_field_name', 'value' => 'desired_value', 'compare' => '=' ] ] ]);
Example
This example queries posts where the custom field color equals blue. It then loops through the results and prints the post titles.
php
<?php $query = new WP_Query([ 'post_type' => 'post', 'meta_query' => [ [ 'key' => 'color', 'value' => 'blue', 'compare' => '=' ] ] ]); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); echo get_the_title() . "\n"; } } else { echo "No posts found."; } wp_reset_postdata();
Output
Post Title 1
Post Title 2
Post Title 3
Common Pitfalls
- Forgetting to use
wp_reset_postdata()after custom queries can break other loops. - Using incorrect
compareoperators or mismatching data types causes no results. - Not specifying
post_typemay return unexpected post types. - Trying to query serialized or complex data without proper handling leads to errors.
php
<?php // Wrong: missing wp_reset_postdata() $query = new WP_Query([ 'meta_query' => [ ['key' => 'color', 'value' => 'red', 'compare' => '='] ] ]); while ($query->have_posts()) { $query->the_post(); echo get_the_title() . "\n"; } // Right: add wp_reset_postdata() wp_reset_postdata();
Quick Reference
Use these tips when querying by custom fields:
- key: The custom field name.
- value: The value to match.
- compare: Operator like '=', '!=', 'LIKE', 'NOT LIKE'.
- type: Data type like 'CHAR', 'NUMERIC' for correct comparison.
- Always reset post data after custom queries.
Key Takeaways
Use WP_Query with meta_query to filter posts by custom fields.
Specify key, value, and compare to control the filtering.
Always call wp_reset_postdata() after your custom query loop.
Check data types and comparison operators to avoid empty results.
Include post_type to target the correct content.