»

Apr
18

WordPress get_pages() meta_key woes

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

Permanent link to this article: http://egeste.net/blog/2010/04/18/wordpress-get-pages-meta-key-woe/

6 comments

  1. Jeroen says:

    Thanks — worked like a charm!

  2. Simon Lachance says:

    Thank you! I was just to the smashing my head on the desk part when I found your post.

  3. Eric says:

    Thanks a lot, WP should have noted this in their codex. :D

  4. Steffen says:

    Thank You!
    Definetly WP should add this to the codex !!

  5. zeally7 says:

    Thank you for this article, it save my time a lot :)

  6. __B__ says:

    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.

Leave a Reply

Your email address will not be published.