thoughtis / cata-co-authors-plus

Common functions, configuration and compatibility fixes for Co-Authors Plus when used in Cata child themes. Not a fork or replacement for CAP.
GNU General Public License v3.0
0 stars 0 forks source link

Social Media Links Block(s) #42

Closed douglas-johnson closed 5 months ago

douglas-johnson commented 5 months ago

Continuing from #33

Since the release of CAP 3.6.0 it should be possible to add custom blocks that utilize coauthor data and to extend the related REST API to provide the a coauthor's social media URLs.

douglas-johnson commented 5 months ago

I made progress on this.

$author['social_links'] is an imaginary value that we would need to add to the API schema.

// update registration of the social link block to use the author context.
add_filter( 'register_block_type_args', function( array $args, string $block_type ): array {

    if ( 'core/social-link' !== $block_type ) {
        return $args;
    }

    return array( ...$args, 'uses_context' => ['co-authors-plus/author'] );
}, 10, 2 );

// when rendering a social link with author context and no existing url, try to fill in the url based on the author.
add_filter( 'render_block', function( string $block_content, array $block, WP_Block $instance): string {

    if ( 'core/social-link' !== (string) $block['blockName'] ) {
        return $block_content;
    }

    if ( ! empty( $block['attrs']['url'] ?? '' ) ) {
        return $block_content;
    }

    $author = $instance->context['co-authors-plus/author'] ?? array();

    if ( empty ( $author ) ) {
        return $block_content;
    }

    $service = $block['attrs']['service'];

    $block['attrs']['url'] = $author['social_links'][$service] ?? '';

    return (new WP_Block( $block ))->render();      
}, 10, 3 );