You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress functions.php中函数与HTML结合实现WooCommerce商品页手册链接

问题根源

  • 你定义的technical_specification_pdf_url()函数用了echo直接输出内容,没有返回值,所以调用时会直接在当前位置打印链接,无法把值传入href属性
  • 函数内没有声明global $post,无法正确获取当前商品ID
  • WooCommerce属性分类存在拼写错误:wc-attibute-class应为wc-attribute-class
  • 字符串拼接语法错误,拼接PHP函数返回值不需要额外加引号

修复后完整代码

// 获取技术说明书PDF链接
function technical_specification_pdf_url (){
    global $post; // 声明全局变量获取当前商品ID
    $terms = get_the_terms( $post->ID, 'wc-attribute-class' ); // 修复属性名拼写错误
    if ( !empty($terms)) {
        $term = array_pop($terms);
        $text = get_field('technical_specification_pdf', $term);
        if (!empty($text)) {
            return $text; // 改为返回值而非直接输出
        }
    }
    return ''; // 无匹配资源时返回空字符串
}

// 输出技术说明书下载按钮
add_action( 'woocommerce_single_product_summary', 'technical_specification_button', 30 );
function technical_specification_button() {
    $pdf_url = technical_specification_pdf_url();
    // 仅当存在PDF链接时输出按钮,避免显示无效空链接
    if(!empty($pdf_url)){
        echo '<a href="'.esc_url($pdf_url).'" target="_blank" rel="noopener noreferrer">technical specification</a>';
    }
}

优化说明

  • 新增esc_url()对链接进行安全转义,符合WordPress编码规范
  • 新增target="_blank"配置让PDF在新标签页打开,避免用户直接离开商品页
  • 增加非空判断逻辑,未上传对应说明书时不会显示无效按钮

内容的提问来源于stack exchange,提问作者Palash Mandal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 04:42:00