如何在Dokan前端供应商仪表盘展示ACF上传的供应商二维码?
故障排查与修正方案
实现目标
在Dokan供应商仪表盘右侧区块,展示当前登录供应商通过自定义字段上传的收款二维码
原始失效代码
// 钩子挂载逻辑 add_action( 'dokan_dashboard_right_widgets', array( $this, 'get_qr_code_widget' ), 10 ); public function get_qr_code_widget() { if ( ! current_user_can( 'dokan_view_sales_report_chart' ) ) { $new_qr= get_field( 'new_qr', 'Vendor'); $Image3_URL=wp_get_attachment_url($new_qr); return; } echo '<img src=" '.$Image3_URL.'" width="200" height="200" alt="Lanka QR" '; }
失效原因定位
- 判断逻辑分支错位
读取二维码字段的代码全部写在「无权限用户」的分支内,且分支末尾直接执行return:无权限用户不会走到图片输出逻辑,有权限的正常供应商用户不会执行字段读取的赋值操作,最终输出的图片src值为空 - ACF取值参数错误
ACF读取用户类自定义字段时,需要传入对应用户的唯一标识(用户ID),直接传入字符串'Vendor'无法匹配到任何用户的字段数据,函数返回空值 - HTML标签未闭合
输出的<img>标签缺少src属性闭合双引号、标签闭合符号>,浏览器无法解析不完整的标签结构 - 图片URL获取逻辑未兼容
未匹配ACF图片字段的返回格式,直接将字段值传给wp_get_attachment_url(),当字段返回格式为图片数组/URL字符串时,函数返回空值
修正后可直接使用的代码
add_action( 'dokan_dashboard_right_widgets', array( $this, 'get_qr_code_widget' ), 10 ); public function get_qr_code_widget() { // 获取当前登录的供应商用户ID $current_vendor_id = dokan_get_current_user_id(); // 权限校验:无权限用户直接终止流程 if ( ! current_user_can( 'dokan_view_sales_report_chart' ) ) { return; } // 按ACF规范读取当前用户的二维码字段,用户字段参数格式为 user_{用户ID} $qr_field_value = get_field( 'new_qr', 'user_' . $current_vendor_id ); // 兼容ACF不同返回格式提取图片URL if ( is_numeric( $qr_field_value ) ) { $qr_url = wp_get_attachment_url( $qr_field_value ); } elseif ( is_array( $qr_field_value ) ) { $qr_url = $qr_field_value['url']; } else { $qr_url = $qr_field_value; } // 未获取到有效图片URL时,直接终止流程避免输出无效链接 if ( empty( $qr_url ) ) { return; } // 输出结构完整的二维码展示模块 printf( '<div class="dokan-widget qr-display-widget" style="padding:20px; background:#fff; border-radius:8px; margin-bottom:20px;"> <h4>店铺收款二维码</h4> <img src="%s" width="200" height="200" alt="店铺收款二维码" style="display:block; margin:12px auto 0;"> </div>', esc_url( $qr_url ) ); }
代码适配说明:已增加空值判断、HTML转义逻辑、多返回格式兼容,可直接替换原有函数代码生效
内容的提问来源于stack exchange,提问作者Ashen
相关产品推荐
相关产品推荐

