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.
i have a question sir if i want to display single post and custom fields then what i should do.
i dont want to display the post with specific custom fields. i want to display all custom fields of post
Hi, thank for the useful tutorial. I have a question, in a wordpress website i set a meta value named “meta_country” and then i set every post with the country of the article, like “us”, “uk”, “fr”… Now I’m trying to add somewhere in the home of the blog a link that show list of all post with a specific country and a specific tag. For example all “UK” post tagged “APPLE”.
I don’t understand how to do that, someone could help me?
great thanks, it help wery well!
Thx!
omg finally THANKS!
I wasnt able to generate any results unless I included “post_type” parameter into the query.
ie: $the_query = new WP_Query(‘post_type=page&meta_key=color’);
Wonderful, just so simple and clean.
Thank you.
@ad Great question! I’m curious too.
Hi,
How could I show posts that DON’T have a specific Custom Field? Any idea?
Thanks!!!
as I know from php it must be meta_key!=’your key’
;just you need to know that “!” means “not”
Beatiful! Many thanks for sharing it. Works like a charm.