Make WordPress Core

Opened 8 years ago

Last modified 9 months ago

#36313 new defect (bug)

get_pages() child_of argument does not work in combination with meta_key/value query

Reported by: marcguay's profile MarcGuay Owned by:
Milestone: Priority: normal
Severity: normal Version: 4.4.2
Component: Posts, Post Types Keywords:
Focuses: Cc:

Description

If you pass both child_of and meta_key/value parameters to the get_pages() function, there are problems. To reproduce:

Create a page structure like so:

Grandparent (id=1)
-Parent (id=2)
--Child (id=3)

Add a custom field to the Child page. Say meta_key='bark' and meta_val='woof'.

Call

get_pages(array(
    'child_of'=>1, 
    'meta_key'=>'bark', 
    'meta_value'=>'woof'
));

And it will return an empty array. The reason this is happening is because in the get_pages function (wp-includes/post.php) on line 4562, the $pages array only contains Child because it's been filtered by the meta_key, but get_page_children(), which is being used to determine which pages are child_of, requires the complete hierarchy of connected pages to determine which are children, and so it returns nothing.

I hope this is helpful. Obviously there are workarounds using loops and get_posts() and people are always suggesting you don't use get_pages() but anyhow, there it is, a bug report. :)

Change History (4)

#1 @MarcGuay
8 years ago

Here's a proposed solution:

	if ( $child_of || $hierarchical ) {
		
		// Get new collection of all post_types queried for
		$all_pages = get_posts(array('post_type' => $r['post_type']));
		
		// Get children based on child_of parameter
		$_pages = get_page_children($child_of, $all_pages);
		
		// And remove elements which were not in the $pages collection queried above 
		foreach ($_pages as $key=>$value){
			if (!in_array($value,$pages)){
				unset($_pages[$key]);
			}
		}
		$pages = $_pages;
	}

#2 @DrewAPicture
8 years ago

Semi-related: #18701

#4 @spacedmonkey
9 months ago

The internals of get_pages changes a lot in #12821. It maybe worth re-validating this is an issue.

Note: See TracTickets for help on using tickets.