Skip to content

Instantly share code, notes, and snippets.

@graemebryson
Last active February 17, 2020 09:49
Show Gist options
  • Save graemebryson/b3c889d4ffed7753bd84205b8ca10d39 to your computer and use it in GitHub Desktop.
Save graemebryson/b3c889d4ffed7753bd84205b8ca10d39 to your computer and use it in GitHub Desktop.
Wordpress — Generate parent/child page group arrays
$id = get_the_id();
$array = output_page_group_array($id);
// Output page group array
var_dump($array);
function output_page_group_array($input) {
// Get target post object from $input
$post = get_post($input);
// Create empty array
$output = array();
// If current page is a child/sibling
if ($post->post_parent) {
// Get current page parent
$parent = get_post($post->post_parent);
// Add parent item ID to array
$output_parent = array($parent->ID);
// Fetch child/sibling items
$output_children = get_pages( array(
'child_of' => $post->post_parent,
) );
// Pluck IDs & mount into array
$output_children = wp_list_pluck( $output_children, 'ID' );
// Merge parent & child arrays
$output = array_merge($output_parent, $output_children);
}
// If current page is a parent
else {
// Add parent item ID to array
$output_parent = array($post->ID);
// Fetch child/sibling items
$output_children = get_pages( array(
'child_of' => $post->ID,
) );
// Pluck IDs & mount into array
$output_children = wp_list_pluck( $output_children, 'ID' );
// Merge parent & child arrays
$output = array_merge($output_parent, $output_children);
}
// Return page group array
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment