为WooCommerce所有数字产品创建固定下载按钮短代码
WooCommerce通用下载按钮短代码修复方案
原代码存在以下几个问题导致无法正常工作:
- 全局
$product对象在短描述上下文里可能未正确初始化,无法获取当前产品数据 - 未过滤产品类型,会给非可下载/虚拟产品也输出按钮
- 未验证用户下载权限,存在未购买即可获取链接的风险
- HTML实体转义错误,输出的是实体字符而非可点击的按钮
修复后的代码如下:
function download_button_shortcode( $atts ) { global $product, $post; // 容错处理:确保能获取当前产品实例 if ( ! $product ) { $product = wc_get_product( $post->ID ); } // 仅对可下载+虚拟产品生效 if ( ! $product || ! $product->is_downloadable() || ! $product->is_virtual() ) { return ''; } $download_files = $product->get_downloads(); // 无下载文件则不输出内容 if ( empty( $download_files ) ) { return ''; } // 验证用户是否已购买该产品 $current_user = wp_get_current_user(); if ( ! wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product->get_id() ) ) { return '<span class="button disabled">请先购买产品</span>'; } // 获取第一个下载文件的链接 $first_download = reset( $download_files ); $download_url = esc_url( $first_download['file'] ); // 返回正常的下载按钮HTML return '<a href="' . $download_url . '" class="button download-button">立即下载</a>'; } add_shortcode( 'download_button', 'download_button_shortcode' );
关键修复说明:
- 增加产品对象容错:当全局
$product不存在时,通过当前文章ID调用wc_get_product()获取产品实例,确保在短描述等场景下能正常工作 - 产品类型校验:通过
is_downloadable()和is_virtual()过滤目标产品,避免无效输出 - 权限验证:使用
wc_customer_bought_product()检查用户是否已购买,防止未授权下载 - 修正HTML输出:移除不必要的实体转义,直接输出可解析的a标签;用
reset()安全获取第一个下载文件(兼容非数字键的下载文件数组) - 友好提示:对未购买用户显示禁用状态的提示按钮,提升用户体验
内容的提问来源于stack exchange,提问作者thuận đinh
相关产品推荐
相关产品推荐

