"More From This Author" Block
Registers a server-rendered block that lists the latest posts by the current post's author, excluding the post being read, to keep readers with writers they like.
Opens WPIDE on
Code
add_action( 'init', function () {
wp_register_script( 'wpide-block-more-from-author', false, array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render' ), '1.0', true );
wp_add_inline_script( 'wpide-block-more-from-author', <<<'JS'
( function ( wp ) {
var el = wp.element.createElement;
wp.blocks.registerBlockType( 'wpide/more-from-author', {
apiVersion: 3,
title: 'More From This Author',
icon: 'admin-users',
category: 'theme',
usesContext: [ 'postId' ],
attributes: { count: { type: 'number', default: 3 } },
edit: function ( props ) {
return el( 'div', wp.blockEditor.useBlockProps(),
el( wp.blockEditor.InspectorControls, null,
el( wp.components.PanelBody, { title: 'Settings' },
el( wp.components.RangeControl, { label: 'Number of posts', min: 1, max: 10, value: props.attributes.count, onChange: function ( v ) { props.setAttributes( { count: v } ); } } )
)
),
el( wp.serverSideRender, { block: 'wpide/more-from-author', attributes: props.attributes, urlQueryArgs: { post_id: props.context.postId || 0 } } )
);
},
save: function () { return null; }
} );
} )( window.wp );
JS
);
register_block_type( 'wpide/more-from-author', array(
'api_version' => 3,
'title' => 'More From This Author',
'category' => 'theme',
'uses_context' => array( 'postId' ),
'editor_script_handles' => array( 'wpide-block-more-from-author' ),
'attributes' => array( 'count' => array( 'type' => 'number', 'default' => 3 ) ),
'render_callback' => function ( $attributes, $content, $block ) {
$post_id = ! empty( $block->context['postId'] ) ? (int) $block->context['postId'] : get_the_ID();
$author = (int) get_post_field( 'post_author', $post_id );
if ( ! $author ) {
return '';
}
$posts = get_posts( array(
'author' => $author,
'post__not_in' => array( $post_id ),
'posts_per_page' => max( 1, min( 10, (int) $attributes['count'] ) ),
'no_found_rows' => true,
) );
if ( ! $posts ) {
return '';
}
$items = '';
foreach ( $posts as $post ) {
$items .= sprintf( '<li><a href="%s">%s</a></li>', esc_url( get_permalink( $post ) ), esc_html( get_the_title( $post ) ) );
}
return sprintf(
'<div %s><h2 class="wp-block-heading">%s</h2><ul>%s</ul></div>',
get_block_wrapper_attributes( array( 'class' => 'wpide-more-from-author' ) ),
esc_html( sprintf( 'More from %s', get_the_author_meta( 'display_name', $author ) ) ),
$items
);
},
) );
} );
Notes
Set how many posts to show in the block settings; place it in the single post template of a block theme or inside a post.
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.