如何在WordPress文章免责声明中为文本添加跳转链接?
如何在WordPress文章免责声明中为文本添加跳转链接?
嘿,这个问题其实很好解决,我来给你一步步说清楚~
你之前的代码里用了esc_html__()函数,这个函数的作用是把文本转义成安全的纯HTML文本——也就是说,如果直接把<a>标签放进去,它会被转成纯文本显示,不会变成可点击的链接。所以我们需要调整写法,把文本和链接分开处理,再拼接起来。
给你两种实用的修改方案,你可以选适合自己的:
方案一:直接指定页面URL(简单直接)
如果你的免责声明页面URL不会轻易改变,直接把URL写进去就行,代码修改后是这样的:
add_filter( 'the_content', 'filter_the_content_in_the_main_loop' ); function filter_the_content_in_the_main_loop( $content ) { // 检查是否在单篇文章的主循环内 if ( is_single() && in_the_loop() && is_main_query() ) { // 处理免责声明的文本部分,确保特殊字符转义 $disclaimer_text = esc_html__( "This website is intended to inform and educate, and shouldn't be taken as financial advice. It also uses affiliate links, including those from Amazon. If you make a purchase via one of the links marked with an *, we might receive a small commission. Find out more ", 'text-domain' ); // 替换成你自己网站的免责声明页面URL,用esc_url确保链接安全 $more_link = '<a href="' . esc_url( 'https://yourwebsite.com/your-disclaimer-page' ) . '">' . esc_html__( 'here', 'text-domain' ) . '</a>'; // 把免责声明(带链接)和原文章内容拼接后返回 return $disclaimer_text . $more_link . $content; } return $content; }
方案二:通过页面ID获取链接(更灵活)
如果担心以后页面URL会变,用页面ID来获取链接更稳妥——就算URL改了,只要页面ID不变,代码就不用动。步骤是:
- 先找到你免责声明页面的ID:在WordPress后台编辑该页面时,地址栏里
post=后面的数字就是页面ID(比如post=123,ID就是123) - 把ID填到代码里,修改后的代码如下:
add_filter( 'the_content', 'filter_the_content_in_the_main_loop' ); function filter_the_content_in_the_main_loop( $content ) { // 检查是否在单篇文章的主循环内 if ( is_single() && in_the_loop() && is_main_query() ) { // 替换成你的免责声明页面ID $disclaimer_page_id = 123; // 通过ID获取页面链接 $disclaimer_link = get_permalink( $disclaimer_page_id ); // 确保链接获取成功后再拼接内容 if ( $disclaimer_link ) { $disclaimer_text = esc_html__( "This website is intended to inform and educate, and shouldn't be taken as financial advice. It also uses affiliate links, including those from Amazon. If you make a purchase via one of the links marked with an *, we might receive a small commission. Find out more ", 'text-domain' ); $more_link = '<a href="' . esc_url( $disclaimer_link ) . '">' . esc_html__( 'here', 'text-domain' ) . '</a>'; return $disclaimer_text . $more_link . $content; } } return $content; }
关键注意事项:
- 一定要用
esc_url()处理链接地址,这是WordPress的安全规范,能防止XSS漏洞 - 文本部分继续用
esc_html__()转义,避免特殊字符导致页面显示异常 - 绝对不要把整个带
<a>标签的字符串放进esc_html__()里,否则标签会被转成纯文本,链接就失效了
备注:内容来源于stack exchange,提问作者WP novice
相关产品推荐
相关产品推荐

