Skip to content

Instantly share code, notes, and snippets.

@Mario-Duarte
Created May 2, 2017 11:18
Show Gist options
  • Save Mario-Duarte/0f0b84be6aa3fdfe586a358fc8214e61 to your computer and use it in GitHub Desktop.
Save Mario-Duarte/0f0b84be6aa3fdfe586a358fc8214e61 to your computer and use it in GitHub Desktop.
WORDPRESS function to get the sibling ID of a given post (grandparent id, greatparent id, etc)
// WORDPRESS function to get the sibling ID of a given post
// this was created to avoid using a repetition patern like:
// $current = $post->ID;
// $parent = $post->post_parent;
// $get_grandparent = get_post($parent);
// $grandparent = $get_grandparent->post_parent;
// $get_greatgrandparent = get_post($grandparent);
// $greatgrandparent = $get_greatgrandparent->post_parent;
// Like described in: http://andyweigel.com/great-grand-parent-ids-in-wordpress/
// this function takes in two arguments, the wordpress post object of the current page ($post)
// and the $depth, this is the number of levels you want to go up so 1 is the parent, 2 is the grandparent ans so on...
function get_siblings($post,$depth = 1) {
$post_ID = $post->ID;
$parent_ID = $post->post_parent;
if ( $depth === 1 ) {
return $parent_ID;
} else {
for ($i=2; $i <= $depth ; $i++) {
if ( $i === 2 ) { $prev_sibling = $parent_ID; } else { $a = $i - 1; $prev_sibling = $sibling_ID_[$a]; }
$get_sibling_ID_[$i] = get_post($prev_sibling);
$sibling_ID_[$i] = $get_sibling_ID_[$i]->post_parent;
} //endfor
return $sibling_ID_[$depth];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment