简体   繁体   中英

Wordpress - Create link to separate author archive inside blog post

We're developing a blog in Wordpress and have come across some functionality that we're having some difficulty implementing.

Our client wants to be able to mention blog users in a blog post, this will then take the end user to the mentioned authors profile. Example below:

"We recently spoke to our newest team member Pete Smith" or "We recently spoke to our newest team member @PeteSmith"

If you were to click on Pete's name it would take you to website.com/authors/petesmith

I know that Wordpress has mentioning functionality built into the comments section, but is there a way to achieve this inside actual blog posts?

Apologies that I can't include any code on this question, there simply is nothing to show you guys.

You can use something like this inside your functions.php:

add_filter('the_content', 'the_content_func');

function the_content_func($content) {
    $ret = preg_replace_callback ( "/(@[A-Za-z]+)/",
        function ($match) {
            $authorName = mb_substr($match[0], 1);
            $author = get_user_by('slug', $authorName);
            if ( ! empty( $author ) )
                return '<a href="' . get_author_posts_url( $author->ID, $author->user_nicename ) . '">' . $author->display_name . '</a>';
            else
                return $authorName;
        },
    $content);
    return $ret;
}

I assume that the text after @ symbol is the author's slug, so inside the filter I search for the given author and if he's found, output the corresponding author profile link with the display name. Otherwise I just output the string without @ symbol & URL.

If I misunderstood your goals, feel free to modify the inner function of preg_replace_callback keeping in mid that $match[0] contains found user slug with @ symbol from the post content.

这是作者存档页面的代码

<a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ), get_the_author_meta( 'user_nicename' ) ); ?>"><?php the_author(); ?></a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM