簡體   English   中英

如何用超鏈接呼應作者? (在 WordPress 中)

[英]How to echo author with hyperlink? (in Wordpress)

這是我正在嘗試做的事情:

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

但它不起作用。

有任何想法嗎? 謝謝!

當您鍵入"時,直到下一個"之后的所有內容都是一個字符串,而不是解釋為代碼。 您可以通過以下方式修復它:

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

只要你鏈接到他們的個人資料,還有一個內置的 function 。

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

編輯

要將作者的姓名添加到鏈接本身,您只需要進一步分解:

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

但是,一旦事情開始變得像這樣復雜,我喜歡切換到sprintfprintf ,它允許您使用占位符:

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

最后兩個函數是 100% 相同的,我只是個人認為后者更具可讀性。

此外,在 WordPress 中,每當您想為 HTML 屬性轉義某些內容時,您使用esc_attr ,否則使用esc_html 這是兩個習慣使用的很棒的功能,這樣您就不會引入奇怪的錯誤和/或安全漏洞。

編輯

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這樣做:

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>"

就個人而言,我總是在 PHP 中使用'和在 HTML 中使用" ,唯一的例外是在 PHP 中我正在做字符串插值,但這是我自己的偏好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM