Skip to content

Instantly share code, notes, and snippets.

@danielcharrua
Created February 3, 2022 11:10
Show Gist options
  • Save danielcharrua/0627927bd6ee80efc1c5e39a0ecdf196 to your computer and use it in GitHub Desktop.
Save danielcharrua/0627927bd6ee80efc1c5e39a0ecdf196 to your computer and use it in GitHub Desktop.
Wordpress Childs in sidebar
<?php
/*
* get_page_depth
* Gets the page depth, calls get_post on every iteration
* https://gist.github.com/1039575
*/
if ( !function_exists( 'get_page_depth' ) ) {
function get_page_depth( $id=0, $depth=0 ) {
global $post;
if ( $id == 0 )
$id = $post->ID;
$page = get_post( $id );
if ( !$page->post_parent ) {
// this page does not have any parent
return $depth;
}
return get_page_depth( $page->post_parent, $depth+1 );
}
}
if ( !function_exists( 'has_children' ) ) {
function has_children() {
global $post;
$pages = get_pages('child_of=' . $post->ID);
if (count($pages) > 0):
return true;
else:
return false;
endif;
}
}
if ( !function_exists( 'is_top_level' ) ) {
function is_top_level() {
global $post, $wpdb;
$current_page = $wpdb->get_var("SELECT post_parent FROM $wpdb->posts WHERE ID = " . $post->ID);
if ($current_page == 0):
return true;
else:
return false;
endif;
}
}
if ( !function_exists( 'get_page_siblings' ) ) {
function get_page_siblings() {
global $post;
$parents = get_post_ancestors( $post->ID );
$page_depth = get_page_depth( $post->ID );
$output = "";
$target_page_id = $page_depth >= 1 ? $post->post_parent : $post->ID;
$target_page = get_post( $target_page_id );
//if page has children show
if( is_top_level() && !has_children() ){
return $output;
} else {
$output .= '<div class="barra-lateral-superior">';
$output .= '<h2>'.$target_page->post_title.'</h2>';
$output .= '<ul>';
if ($page_depth != 0){
//si estoy en una categoria menor que la maxima padre, muestro todo el arbol descendiente
$output .= wp_list_pages("title_li=&child_of={$target_page_id}&depth=0&echo=0&sort_column=menu_order");
} else {
//si estoy en la categoria padre de padres, no mostrar tanta profundidad de hijos, nivel 2 esta ok
$output .= wp_list_pages("title_li=&child_of={$target_page_id}&depth=2&echo=0&sort_column=menu_order");
}
$output .= '</ul>';
$output .= '</div>';
}
return $output;
}
}
add_shortcode('charrua_sidebar_childs', 'get_page_siblings');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment