在我的WordPress网站上,我为作者网站链接创建了一个自定义字段,但我不知道如何使其成为超链接。人们必须能够点击它来浏览该网站。
此时,它只显示原始文本,如:"www.example.com"
我的代码是:
<?php echo get_post_meta($post->ID, 'Author Website', true); ?>
为了避免损坏HTML,您需要首先检查链接是否存在,然后显示它。
要做到这一点,您需要使用if语句:
if( $link = get_post_meta( $post->ID, 'Author Website', true ) )
至于链接本身,一个常规的HTML锚标记如下所示:
<a href="http://www.example.com/">http://www.example.com/</a>
例如,我使用的是sprintf函数,它将用正确的值替换%s:
if( $link = get_post_meta( $post->ID, 'Author Website', true ) ) {
sprintf(
'<a href="%s" target="_blank">%s</a>',
esc_attr( $link ),
$link
);
}
在这个例子中,我使用esc_attr()来确保链接不会破坏页面布局。
希望这对你有用:)