Skip to content

Author Name Block: Link to Author URL #75151

Description

@BrookeDot

When you add the Author Name Block (core/post-author-name) to the post, the only option is to link to the author's archive. It would be nice to be able to link elsewhere, such as the author's website.

https://wordpress.org/documentation/article/post-author-name-block/

What problem does this address?

Customizing the Author Name Block to include the URL makes it more flexible. Otherwise, a custom block or the HTML_Tag_Processor must be used.

What is your proposed solution?

Update the "Link to Authors Archive" to show a dropdown of places it can be linked to.

Workaround:

Use WP_HTML_Tag_Processor

function add_author_url_to_name_block($block_content, $block)
{
    $author_id = $block['context']['postAuthor'] ?? get_post_field('post_author');

    if (! $author_id) {
        return $block_content;
    }

    $author_url = get_the_author_meta('user_url', $author_id);
    
    if (empty($author_url)) {
        return $block_content;
    }
    
    $processor = new WP_HTML_Tag_Processor($block_content);

    if ($processor->next_tag('a')) {
        return $block_content;
    }

    $processor = new WP_HTML_Tag_Processor($block_content);
    
    if ($processor->next_tag()) {
        $tag_name = $processor->get_tag();
        
        $existing_class = $processor->get_attribute('class');
        $attributes = $existing_class ? sprintf(' class="%s"', esc_attr($existing_class)) : '';

        preg_match('/<[^>]+>(.*?)<\/[^>]+>/s', $block_content, $matches);
        $inner_content = $matches[1] ?? $block_content;

        return sprintf(
            '<%1$s%2$s><a href="%3$s" target="_blank" rel="noopener noreferrer" class="wp-block-post-author-name__link">%4$s</a></%1$s>',
            $tag_name,
            $attributes,
            esc_url($author_url),
            $inner_content
        );
    }

    return $block_content;
}


Related: #40157 (regarding editing the author's text)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions