Greg Smith

Web Developer

loading

WordPress: get subpages with get_pages() and meta_key

2 comments

This one had me stumped for a while.

I wanted to get a list of all pages which had a certain custom field. This can be easily done by passing the meta_key parameter to the get_pages() function, which returns an array of post objects. For example, if you wanted to get a list of all pages with the custom field ‘test’, you would do:

1
$pages = get_pages('meta_key=test');
$pages = get_pages('meta_key=test');

This works fine for top-level pages with the custom field ‘test’, but child pages are inexplicably ignored. This doesn’t seem to be mentioned anywhere in the WordPress Codex and was a source of much confusion to me.

The solution: hierarchical

Another parameter of the get_pages() function is hierarchical, which is used to display subpages in an indented fashion below their parent, and defaults to true. Setting this to false, we get our expected results from get_pages():

1
$pages = get_pages('meta_key=test&hierarchical=0');
$pages = get_pages('meta_key=test&hierarchical=0');

Any pages or subpages with the custom field ‘test’ will now be returned.

2 Comments

  1. Posted February 10, 2012 at 10:09 pm

    Had the same problem, but now it's fixed. Thank you very much!

  2. Posted July 17, 2012 at 5:29 pm

    I can`t believe it, thanks for the solution!

Post a Comment

Your email is never shared. Required fields are marked *

*
*