如何在mPDF中正确显示ACF复选框字段的取值
问题排查结果
你的代码有两处核心错误,直接导致复选框值无法输出:
- 取值逻辑错误:
get_field_object()返回的是ACF字段的完整配置数组(包含字段类型、所有可选值、字段设置等元数据),不是用户选中的实际值,直接对这个返回数组做in_array()判断永远无法命中条件。 - 变量作用域错误:你在
congres_redirect函数内定义的$offer2for10没有作为参数传入view_conferinta(),PDF生成函数的作用域里根本不存在这个变量,对应位置自然没有任何输出。
另外你没有给优惠字段设置默认值,复选框未选中时会触发PHP未定义变量警告,也可能导致PDF生成异常。
调整步骤
- 修正复选框取值:直接用
get_field()获取选中值即可,若坚持用get_field_object(),需要取返回数组中value键对应的实际选中内容。 - 补全函数传参,把生成的优惠文本传入PDF渲染函数。
- 给优惠文本设置默认空值,兼容未选中任何选项的场景。
修正后可直接使用的代码
add_action('init', 'congres_redirect'); function congres_redirect() { if(isset($_GET['offer'])) { $offerid = $_GET['offer']; $restname = get_field('restaurant_name', $offerid); // 直接获取复选框选中值 $offer = get_field('restaurant_offer', $offerid); // 初始化优惠变量,设置默认空值 $offer2for10 = ''; // 兼容复选框多选/单选两种返回格式判断 if( (is_array($offer) && in_array('2courses10', $offer)) || $offer == '2courses10' ) { $offer2for10 = '2 courses for 10'; } $randNum = strtoupper(generateRandomString(5)); $date = date("Ymd"); $namecode = strtoupper(str_replace(' ', '', $restname)); $namestr = substr($namecode, 0, 6); // 把优惠变量传入PDF生成函数 view_conferinta($restname, $randNum, $date, $namecode, $namestr, $offer2for10); } } // 新增$offer2for10参数接收 function view_conferinta($restname, $randNum, $date, $namecode, $namestr, $offer2for10) { $output = '<html> <head><title>'.$restname.' | Eat Leeds</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head> <body style="font-family:chelvetica;"> <table class="voucher-content" width="100%"> <tr> <td width="60%"></td> <td width="40%"> <table> <tr class="inner-voucher"> <td class="offer-details" style="color: #fff !important;">'.$restname.'</td> </tr> <tr class="inner-voucher"> <td class="offer-details" style="color: #fff !important;">'.$offer2for10.'</td> </tr> <tr> <td style="vertical-align: top; padding-top: 20px; padding-left: 280px; color: #fff;"><div class="vouchercode">Voucher Code: EL-'.$namestr.''.$date.'-'.$randNum.'</div></td> </tr> </table> </td> </tr> </table> </body> </html>'; require_once __DIR__ . '/mpdf/vendor/autoload.php'; $mpdf = new \Mpdf\Mpdf(['debug' => true]); $mpdf->WriteHTML($output); $mpdf->Output('eatleeds-EL-'.$namestr.''.$date.'-'.$randNum.'.pdf','I'); exit; }
如果需要输出复选框的多个选中值,直接遍历
$offer数组拼接字符串即可,ACF复选框字段保存的选中值始终是「单选返回字符串、多选返回一维数组」的格式。
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

