"Pages in This Section" Block
Registers a server-rendered block that lists the other pages sharing the current page's parent, with the current page marked, giving every section of a large site its own side navigation.
Opens WPIDE on
Code
add_action( 'init', function () {
wp_register_script( 'wpide-block-sibling-pages', false, array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-server-side-render' ), '1.0', true );
wp_add_inline_script( 'wpide-block-sibling-pages', <<<'JS'
( function ( wp ) {
var el = wp.element.createElement;
wp.blocks.registerBlockType( 'wpide/sibling-pages', {
apiVersion: 3,
title: 'Pages in This Section',
icon: 'list-view',
category: 'theme',
usesContext: [ 'postId' ],
edit: function ( props ) {
return el( 'div', wp.blockEditor.useBlockProps(),
el( wp.serverSideRender, { block: 'wpide/sibling-pages', urlQueryArgs: { post_id: props.context.postId || 0 } } )
);
},
save: function () { return null; }
} );
} )( window.wp );
JS
);
register_block_type( 'wpide/sibling-pages', array(
'api_version' => 3,
'title' => 'Pages in This Section',
'category' => 'theme',
'uses_context' => array( 'postId' ),
'editor_script_handles' => array( 'wpide-block-sibling-pages' ),
'render_callback' => function ( $attributes, $content, $block ) {
$page_id = ! empty( $block->context['postId'] ) ? (int) $block->context['postId'] : ( isset( $_GET['post_id'] ) ? absint( $_GET['post_id'] ) : get_the_ID() );
if ( ! $page_id || 'page' !== get_post_type( $page_id ) ) {
return '';
}
$parent = (int) wp_get_post_parent_id( $page_id );
$pages = get_pages( array(
'parent' => $parent ? $parent : $page_id,
'sort_column' => 'menu_order,post_title',
) );
if ( ! $pages ) {
return '';
}
$items = '';
foreach ( $pages as $page ) {
$current = (int) $page->ID === $page_id;
$items .= sprintf(
'<li%s><a href="%s"%s>%s</a></li>',
$current ? ' class="is-current"' : '',
esc_url( get_permalink( $page ) ),
$current ? ' aria-current="page"' : '',
esc_html( get_the_title( $page ) )
);
}
$label = $parent ? get_the_title( $parent ) : get_the_title( $page_id );
return sprintf( '<nav %s aria-label="%s"><ul>%s</ul></nav>', get_block_wrapper_attributes( array( 'class' => 'wpide-sibling-pages' ) ), esc_attr( $label ), $items );
},
) );
} );
Notes
On a top-level page it lists that page's children instead; add the block to a page template so every page in the section gets it.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.