Accessing post->ID outside of the loop for listing child pages

I’m wanting to list child pages of my current page in the sidebar of theme. However my sidebar (left side) is before the loop in the template and the post->ID won’t return anything if it’s before the loop.

My current code:

Read More
<?php

wp_list_pages('title_li=&child_of='.$post->ID); 

?>

I’ve read something about calling a global variable to access this but haven’t had any luck thus far.

Any help would be appreciated.

Related posts

4 comments

  1. … the post->ID won’t return anything if it’s before the loop

    Generally speaking, this is false. The $post variable is set well before the Loop starts in your theme, for most pages. The main query “primes” that variable to the first post in the Loop. That said, depending on this variable outside the Loop is not the most reliable approach. More reliable, would be to use get_queried_object.

    $qobj = get_queried_object();
    wp_list_pages('title_li=&child_of='.$qobj->ID);
    

    Because get_queried_object returns different information depending on the page you are on, you are also better off checking for the page type before using it.

    if (is_page()) {
        $qobj = get_queried_object();
        wp_list_pages('title_li=&child_of='.$qobj->ID);
    }
    

    Or check the object itself.

    $qobj = get_queried_object();
    if (isset($qobj->post_type) && 'page' == $qobj->post_type) {
      wp_list_pages('title_li=&child_of='.$qobj->ID);
    }
    

    Those are just examples. I don’t know what your precise conditions are.

  2. Try this:

    // get the post id
    $post_id = get_queried_object_id();
    
    // get the children
    $children = get_pages('child_of' => $post_id);
    
    //output them
    if( count( $children ) != 0 ) {
        echo "<ul>";
        foreach ($children as $child) {
            // if we only want children, not grandchildren
            if ($child->post_parent == $post_id) {
                echo "<li><a href="" . get_permalink($child->ID) . "">";
                echo $child->post_title;
                echo "</a></li>";
            }
        }
        echo "</ul>";
    }
    
  3. try to make code like

    global $post;
    var_dump($post);//test values in $post
    wp_list_pages('title_li=&child_of='.$post->ID);
    
  4. There’s really not enough information to give an accurate answer here, but if your suspicion is correct, try replacing $post->ID with get_the_ID().

Comments are closed.