WordPress Custom Fields [ Part 2 ] Final
Only Display Posts with a Specific Custom Field
The best part about query_posts function in WordPress is that it has a parameter for custom fields. So we can use it to create a loop that only displays posts with a specific custom field key and/or value. All you would have to do is enter the query_posts tag above your post’s loop statement. Let’s say you want to display posts that you wrote while listening to a music as opposed to posts that you wrote in reflection of the book you read.
You will paste the following query before you start the loop:
query_posts('meta_key=music');
This code will list posts with the meta key music present.
Let’s say you want to customize it a bit more by saying you want to display posts that you wrote while listening to Eminem’s Songs. Well then, you will customize the codes like this:
query_posts('meta_key=music&meta_value=Eminem');
How to Style Individual Posts with Custom Fields
Want an entirely different look for your WordPress single posts? Well you can do this by adding custom post classes via custom field. We have written an entire article on how to style each WordPress post differently, so this code is based on that tutorial.
First thing you need to do is create a custom field with the name “post-class” and then add the value which will be your class. So in this example, we will use “anniversary”. Once you have done that, then add the following code inside your loop:
ID, 'post-class'); ?>
Now if you look in your loop, there is a post_class function inside a div class. Just replace that with something like this:
Alternatively, you can also add inline css to the header of your single pages. If that is something that you are looking to do, then open your header.php file, and insert the following code somewhere between the head tags.
ID, 'customstyle', true); if (!empty($customstyle)) { ?>