If this tutorial is not what you were looking for, you still have any questions, suggestions or concerns - feel free to let us know. Please help us to serve you better!

Your Name

Your Email

Your Message (required)

captcha

How to display posts by custom fields

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'
			));

  • Marzia

    Hello,
    i don’t know if anyone can help me with this…
    I would like to display inside my post the related posts by specific custom field value that is determined from the wp admin panel. Example: in my post having a custom field key named “client”, value “name of the client” (this one written in the edit post in wp admin) I would like to display a list of post having the same value.
    If each post has different values I cannot use the line above in my single:
    ‘meta_value’ => ‘your_custom_field_value’.
    Sorry I’m not expert in php. Any clues to help?
    Thank you very much! Marzia