2

I'm trying to make a shortcode I can put into a widget that will show the siblings if there are any otherwise show the children.

Here is my code I've started with:

//sidebar siblings menu
function rt_list_children() {
    global $post;
    $page = $post->ID;
    if ( $post->post_parent ) {
        $page = $post->post_parent;
    }
    $children = wp_list_pages( array(
        'child_of' => $page,
        'title_li'    => '',
        'echo' => '0',
    ) );

    if ($children) {
       $output = '<ul>';
       $output .= $children;
       $output .= '</ul>';
    } else {
       $output = '';
    }
    return $output;
}
add_shortcode ('sidebar-menu','rt_list_children');

Then, in a html widget, I paste [sidebar-menu].

Right now, The menu only shows up on pages that are children and have siblings. It shows the siblings.

Ideally, I'd like if it's a top level page without children, don't show.

If it's a top level page with children, show the children.

If it's a child page with siblings, show the siblings.

Is this close?

Maybe there's a way to do this without creating parents, but by simply using the menu i've setup in appearances/menu and it will only show the options for children i've set there?

2

Yes, you're close. What you want is something like this:

function rt_list_children() {
    global $post;
    $output = '';

    if ( $post->post_parent ) {  // if it's a child page
        $siblings = wp_list_pages( array(
            'child_of' => $post->post_parent,
            'title_li'    => '',
            'echo' => '0',
        ) );
        if ( $siblings ) {  // it has siblings
            $children = $siblings;
        } else {  // it has no siblings, so show its children
            $children = wp_list_pages( array(
                'child_of' => $post->ID,
                'title_li'    => '',
                'echo' => '0',
            ) );
        }
    } else {  // it's a top level page, show its children
        $children = wp_list_pages( array(
            'child_of' => $post->ID,
            'title_li'    => '',
            'echo' => '0',
        ) );
    }

    if ( $children ) {
       $output = '<ul>' . $children . '</ul>';
    }
    return $output;
}
add_shortcode ('sidebar-menu','rt_list_children');

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.