This tutorial will show you how to query your WordPress posts by custom field values.
Custom queries are very useful when you have a variety of post types with lots custom fields. Your custom fields give you some nice data points to search (query) from. For this tutorial we’ll use events as an example. Let’s say we want to query specific event posts based on some custom fields:
- Event Access (public vs private)
- Event Type (main vs something else)
We’re going to use the
WP_Query class to construct our custom query. We’ll also use
meta_query to create arrays for our criteria.
<?php // Event query arguments $event_query_args = array( 'post_type' => 'event', 'posts_per_page' => 10, 'meta_query' => array( array( 'key' => 'event_access', 'value' => 'public' ), array( 'key' => 'event_type', 'value' => 'Main Event' ) ) ); // Event query $event_query = new WP_Query( $event_query_args ); ?>
Now we’ll do a check for our custom query and then loop through the posts.
<?php if ( $event_query->have_posts() ) : ?> <?php while ( $event_query->have_posts() ) : $event_query->the_post(); ?> // do your loop HTML here <?php endwhile; ?> <?php endif; ?>
This will fetch the most recent 10 event post types that meet the following criteria:
Event Access = public
Event Type = Main Event
Note – you must use the custom field name as the key (i.e. Event Access -> event_access).
I hope this helps you in your custom querying!