Last active
          July 29, 2022 11:25 
        
      - 
      
 - 
        
Save lukaszklis/1247306 to your computer and use it in GitHub Desktop.  
    WordPress: check if a current page has children, if so display them, if not display all pages on the same level as current page
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | <?php | |
| // Your functions.php content | |
| function has_children() { | |
| global $post; | |
| $pages = get_pages('child_of=' . $post->ID); | |
| return count($pages); | |
| } | |
| function is_top_level() { | |
| global $post, $wpdb; | |
| $current_page = $wpdb->get_var("SELECT post_parent FROM $wpdb->posts WHERE ID = " . $post->ID); | |
| return $current_page; | |
| } | |
| // Somewhere in your template | |
| echo '<ul>'; | |
| $base_args = array( | |
| 'hierarchical' => 0 | |
| ); | |
| if (has_children()) { | |
| $args = array( | |
| 'child_of' => $post->ID, | |
| 'parent' => $post->ID | |
| ); | |
| } else { | |
| if (is_top_level()) { | |
| $args = array( | |
| 'child_of' => $post->post_parent, | |
| 'parent' => $post->post_parent | |
| ); | |
| } else { | |
| $args = array( | |
| 'parent' => 0 | |
| ); | |
| } | |
| } | |
| $args = array_merge($base_args, $args); | |
| $pages = get_pages($args); | |
| foreach ($pages as $page) { | |
| echo '<li><a href="' . get_permalink($page->ID) . '">' . $page->post_title . '</a></li>'; | |
| } | |
| echo '</ul>'; | 
Thanks your sharing, also developers can use that:
if ( !empty(get_pages(['child_of' => get_queried_object_id()) { // page has children(s) } ) else { // page has no children(s) }
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Thanks a lot mate !! you save my day , check this http://stackoverflow.com/questions/19738002/solved-wrap-post-type-post-with-nested-child-post-inside-ul
Well , here some potatoes :D