- Web templates
- E-commerce Templates
- CMS & Blog Templates
- Facebook Templates
- Website Builders
How to display posts by custom fields
April 8, 2011
This tutorial will show you how to display posts by custom field values in WordPress.
Before you start this tutorial please make sure you learned how to add pages, create page templates and learned how to use custom fileds in WordPress.
1. Access your theme directory (wp-content/themes/theme###)
2. Create new page, create new page template and assign it to the page.
3. Open the created page template file
To display a posts by specific tag we’ll use the WordPress function "query_posts()"
The page template file content would be as follows:
<?php /* Template Name: Posts by Tag */ ?> <?php get_header(); ?> <div class="container"> <div class="indent"> <?php query_posts(array( 'meta_key' => 'your_custom_field_key', 'meta_value' => 'your_custom_field_value' )); if ( have_posts() ) while ( have_posts() ) : the_post(); echo '<li>'; the_title(); echo '</li>'; endwhile; wp_reset_query(); ?> </div> </div> <?php get_footer(); ?> Replace the your_custom_field_key with custom field key and your_custom_field_value with custom key value
As you can see we inserted the "query_posts()" function:
query_posts(array( 'meta_key' => 'your_custom_field_key', 'meta_value' => 'your_custom_field_value' ));
Activated the posts loop that will allow WordPress yto display posts:
if ( have_posts() ) while ( have_posts() ) : the_post(); ... endwhile;
Added some HTML markup for the posts list.
echo '<li>'; the_title(); echo '</li>';
And closed the "query_posts()" function after the loop.
wp_reset_query(); ?>
You can also define the specific category for the posts display so the page will display the posts by custom fields from the specific category. To do this modify the query the gollowing way:
query_posts(array( 'meta_key' => 'your_custom_field_key', 'meta_value' => 'your_custom_field_value', 'category_name' => 'your_category_name' ));