Posts Tagged ‘query pages’

WordPress query pages (not posts) using custom fields

Monday, December 5th, 2011

First off, let me say that I am not a master coder and am still learning. Also, I spent many a precious hour trying to find a solution for this. There are probably many easier/better ways to do it, but this definitely works. If you have found a better way, please post it in the comments section.

The Situation
Now, let me explain what it was that I wanted to do. I had several WordPress pages (not posts) with custom fields already set up. I wanted to have only those pages with a particular custom field name appear on a certain page. So, I wanted to create a custom query that would return only those pages with the custom field name.

The Problem
The problem was that most every query that I tried would not return any of the pages. Each one would only return posts (not pages) with that custom field.

I originally started working with query_posts, but I kept running into a problem with the query returning pages that did not have the custom field and also returning multiple instances of the results (probably an issue with where I had placed the wp_reset_query). I also tried this solution with no luck.

The Solution
Many thanks to Ben at Binary Moon for this article and also to this thread on the WordPress forums that helped me quite a bit.

<?php
$pages = array(
'post_type' => 'page',
'meta_key' => 'your_custom_field_name',
'order' => 'asc'
);
$queryObject = new WP_Query($pages);
?>

<?php if ( $queryObject->have_posts() )
while (
$queryObject->have_posts() ) :
$queryObject->the_post();
?>

<!-- Loop or custom code goes here -->

<?php endwhile; ?>

Be sure to:
1.) Set the custom field on your pages, and publish the pages.
2.) Paste the code above into your loop/page template file/wherever you want the results to appear.
3.) Change the bit with your_custom_field_name to the custom field that you have set up on the pages that you want to query.

For more ways to customize and use the information from the custom fields, check out Part I and Part II at the Perishable Press.

Share