Every once in a while you run into a problem that makes you scratch your head… and eventually maybe smash it against your desk a few times. This was definitely one of those.
get_pages() is a method that returns an array of $post objects (which is very well documented here). There are multiple arguments you can pass to get_pages() for the purpose of filtering the results you get back (these args are well documented here). For example, if you only want to retrieve sub-pages of the current page, you could say:
$pages = get_pages("child_of=".$post->ID);
One of the args you can specify is the meta_key arg, which will only return pages that contain the meta_key you specify. (See: Custom Fields) This is where I ran into some trouble.
It turns out that get_pages has an argument called hierarchical, which according to the codex does the following:
- hierarchical
- (boolean) Display sub-Pages in an indented manner below their parent or list the Pages inline. The default is true (display sub-Pages indented below the parent list item). Valid values:
- 1 (true) – default
- 0 (false)
What’s not intuitive about this argument is that it will filter subpages, (that is, not top-level pages) when using the meta_key arg. Here’s an example:
Data Set
- Homepage
- About
- Foo
- Bar (This item has a meta_key named banner_title)
Code
count(get_pages("meta_key=banner_title"));
Output: 0
The output indicates that 0 results were returned, despite the fact that we have a page with a meta_key named banner_title. So lets try something different.
Code
count(get_pages("meta_key=banner_title&hierarchical=0"));
Output: 1
Ah, now we’re getting the results we want.
TL;DR – you have to use the hierarchical=0 arg to list all pages that contain your meta_key, otherwise you will only get top-level pages.
-Egeste
6 comments
Jeroen says:
July 29, 2010 at 4:01 pm (UTC 0 )
Thanks — worked like a charm!
Simon Lachance says:
August 18, 2010 at 5:59 pm (UTC 0 )
Thank you! I was just to the smashing my head on the desk part when I found your post.
Eric says:
August 23, 2010 at 3:48 pm (UTC 0 )
Thanks a lot, WP should have noted this in their codex.
Steffen says:
September 7, 2010 at 6:00 pm (UTC 0 )
Thank You!
Definetly WP should add this to the codex !!
zeally7 says:
April 3, 2011 at 10:58 am (UTC 0 )
Thank you for this article, it save my time a lot
__B__ says:
September 20, 2011 at 4:17 am (UTC 0 )
Thanks man. Really, thanks. I’m in a “freelance” project right now, and only needed this info to finish it. Your little minutes of a blog post saved a bunch of hours.