Nov 09

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

One Response to “Wordpress get_pages() meta_key woes”

  1. Thank you so much for posting that. I was about to spend 5 hours on a wild-goose chase myself.

Leave a Reply

preload preload preload