Recently one of our users asked us how to display WordPress posts only if a specific custom field was present. After replying back with the answer, we thought it would best if we share with everyone else, so the larger community can benefit from it as well.
You need to have a fair understanding of how WordPress loops work because we will call these parameters in a WordPress query.
The example code below will only show posts that have a custom field color present no matter what value the color field has. You would need to paste this loop code wherever you want to posts to show. Most likely in a custom WordPress page template.
<?php // The Query to show a specific Custom Field $the_query = new WP_Query('meta_key=color'); // The Loop while ( $the_query->have_posts() ) : $the_query->the_post(); the_title(); the_content(); endwhile; // Reset Post Data wp_reset_postdata(); ?>
Now if you want to show posts that has a custom field with a specific value, then you just have to change the query like this:
$the_query = new WP_Query( 'meta_value=blue' );
Now if you want to stress out the key and value for example you only want to pull posts that has a custom field key color and the value as blue, then your query code will look liks this:
$the_query = new WP_Query( array( 'meta_key' => 'color', 'meta_value' => 'blue' ) );
There are a lot more custom parameters that you can use while working on your sites. Just refer to the Codex page for WP_Query Parameters.