1

I have written the function below to list the current pages child pages. Now what I am trying to do is list the children of a specific page using its slug in the shortcode.

Is it possible to sneak an attribute into wp_list_pages? So for example if you wanted to list the pages of a certain parents slug you could specify the parent in the shortcode like this [childpages parent=”projects″] I am kind of stumped here

function list_child_pages()
    {
    global $post;
    $childpages = wp_list_pages('sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0');
    if ($childpages)
        {
        $string = '<ul>' . $childpages . '</ul>';
        }

    return $string;
    }

add_shortcode('childpages', 'list_child_pages');
2

wp_list_pages can take child_of param, to show only pages that are children of given page. But you have to pass the ID of that parent page (so you can't put a slug in there).

But you can use get_page_by_path to get a page object based on slug of the page.

And another thing you have to do is to add some params to your shortcode.

So here's the code:

function childpages_shortcode_callback( $atts ) {
    $atts = shortcode_atts( array(
        'parent' => false,
    ), $atts, 'childpages' );

    $parent_id = false;
    if ( $atts['parent'] ) {
        $parent = get_page_by_path( $atts['parent'] ); 
        if ( $parent ) {
            $parent_id = $parent->ID;
        }
    } else { // if no parent passed, then show children of current page
        $parent_id = get_the_ID();
    }

    $result = '';
    if ( ! $parent_id ) {  // don't waste time getting pages, if we couldn't get parent page
         return $result;
    }

    $childpages = wp_list_pages( array(
        'sort_column' => 'menu_order',
        'title_li' => '',
        'child_of' => $parent_id,
        'echo' => 0
    ) );

    if ( $childpages ) {
        $result = '<ul>' . $childpages . '</ul>';
    }

    return $result;
}
add_shortcode( 'childpages', 'childpages_shortcode_callback' );
  • Why thank you very much! This is a very clever method and I have learned a couple of new functions. If you have the time, could you post an example using the child ID instead of the path/slug? I think I will completely understand then. Thanks again – Jalapeno Jack Mar 30 '19 at 7:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.