简体   繁体   中英

How to echo author with hyperlink? (in Wordpress)

Here's what I'm trying to do:

echo "<a href='http://www.mywebsite.com'><?php echo get_the_author(); ?></a>";

But it doesn't work.

Any ideas? thanks!

When you type " , everything after that until the next " is a string and not interpreted as code. You can fix it by doing:

echo "<a href='http://www.mywebsite.com'>" . esc_html(get_the_author()) . "</a>";

There is also a built-in function for the whole thing, as long as you are linking to their profile.

https://developer.wordpress.org/reference/functions/get_the_author_posts_link/

edit

To add the author's name into the link itself, you just need to break things up some more:

echo "<a href='http://www.mywebsite.com/" . esc_attr(get_the_author()) . "'>" . esc_html(get_the_author()) . "</a>";

However, once things start to get complicated like this I like to switch to sprintf or printf which allows you to use placeholders:

echo sprintf("<a href='http://www.mywebsite.com/%1$s">%2$s</a>, esc_attr(get_the_author()), esc_html(get_the_author()));

The last two functions are 100% identical, I just personally think the latter is more readable.

Also, in WordPress whenever you want to escape something for HTML attributes you use esc_attr and otherwise you use esc_html . These are two great functions to get used to always using so that you don't introduce weird bugs and/or security vulnerabilities.

edit

Both PHP and HTML support two quotes, either ' or " . If you use for PHP then you'll want to use the other for HTML. In PHP, you can also use a \ to escape the next quote. So all of these will do that same:

echo '<font color="red"><a href="mywebsite.com"' . esc_attr(get_the_author()) . '">' . esc_html(get_the_author()) . '</a></font>'
echo "<font color='red'><a href='mywebsite.com" . esc_attr(get_the_author()) . "'>" . esc_html(get_the_author()) . "</a></font>"
echo "<font color=\"red\"><a href=\"mywebsite.com\"" . esc_attr(get_the_author()) . "\">" . esc_html(get_the_author()) . "</a></font>"

Personally, I use ' in PHP and " in HTML always, with the sole exception in PHP where I'm doing string interpolation, but that is my own preference.

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