WordPress.org

Make WordPress Core

Opened 4 years ago

Last modified 6 months ago

#36313 new defect (bug)

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

Reported by: MarcGuay Owned by:
Milestone: Priority: normal
Severity: normal Version: 4.4.2
Component: Posts, Post Types Keywords:
Focuses: Cc:
PR Number:

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 (2)

#1 @MarcGuay
4 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
4 years ago

Semi-related: #18701

Note: See TracTickets for help on using tickets.