如何在WooCommerce PDF发票中替换SKU为产品ACF字段Internal ID
问题
我是技术新手,正尝试从WooCommerce产品中调用ACF字段「Internal ID」的值,将其显示在PDF发票中,但在获取该信息时遇到了问题。
我的ACF字段设置:字段显示名称为「Internal ID」,字段类型为文本,已为对应产品设置好字段值。
我需要将该字段值添加到以下PDF发票代码中:
<?php do_action( 'wpo_wcpdf_before_order_details', $this->get_type(), $this->order ); ?> <table class="order-details"> <thead> <tr> <th class="product"><?php _e( 'Product Name', 'woocommerce-pdf-invoices-packing-slips' ); ?></th> <th class="reference"><?php _e( 'Product Reference', 'woocommerce-pdf-invoices-packing-slips' ); ?></th> <th class="pick_quantity"><?php _e( 'Pick Qty', 'woocommerce-pdf-invoices-packing-slips' ); ?></th> <th class="price"><?php _e( 'Price ex.VAT', 'woocommerce-pdf-invoices-packing-slips' ); ?></th> <th class="vat"><?php _e( 'VAT', 'woocommerce-pdf-invoices-packing-slips' ); ?></th> <th class="price"><?php _e( 'Price inc.VAT', 'woocommerce-pdf-invoices-packing-slips' ); ?></th> </tr> </thead> <tbody> <?php foreach ( $this->get_order_items() as $item_id => $item ) : ?> <tr class="<?php echo apply_filters( 'wpo_wcpdf_item_row_class', 'item-'.$item_id, $this->get_type(), $this->order, $item_id ); ?>"> <td class="product"> <?php $description_label = __( 'Description', 'woocommerce-pdf-invoices-packing-slips' ); // registering alternate label translation ?> <span class="item-name"><?php echo $item['name']; ?></span> <?php do_action( 'wpo_wcpdf_after_item_meta', $this->get_type(), $item, $this->order ); ?> </td> <td class="reference"> <?php if ( ! empty( $item['sku'] ) ) : ?><dt class="sku"><dd class="sku"><?php echo $item['sku']; ?></dd><?php endif; ?> <?php echo $item['thumbnail']?> </td> <td class="pick_quantity"><?php echo $item['quantity']; ?></td> <td class="price"><?php echo $item['line_total']; ?></td> <td class="vat"><?php echo $item['line_tax']; ?></td> <td class="price"><?php echo $item['order_price']; ?></td> </tr> <?php endforeach; ?> </tbody> <tfoot>
我希望将如下代码行替换为显示ACF的「Internal ID」值:
<?php if ( ! empty( $item['sku'] ) ) : ?><dt class="sku"><dd class="sku"><?php echo $item['sku']; ?></dd><?php endif; ?>
解决方案
替换上述代码段,使用以下代码即可显示ACF字段「Internal ID」的值:
<?php // 获取当前订单商品对应的产品ID(兼容可变产品) $product_id = $item['product_id'] ?? $item['variation_id']; // 调用ACF函数获取字段值,替换为你的字段slug $internal_id = get_field('internal_id', $product_id); if ( ! empty( $internal_id ) ) : ?> <dt class="internal-id">Internal ID:</dt> <dd class="internal-id"><?php echo esc_html( $internal_id ); ?></dd> <?php endif; ?>
关键说明:
- 字段Slug确认:请确保代码中的
'internal_id'是你ACF字段的实际slug(在ACF字段编辑页面查看,通常为小写字母加下划线,与显示名称「Internal ID」对应)。 - 兼容可变产品:代码中
$item['product_id'] ?? $item['variation_id']会自动适配简单产品和可变产品,确保能读取对应产品/变体的ACF字段。 - 安全输出:使用
esc_html()确保字段值安全输出,避免XSS风险。 - 保留SKU:如果需要同时显示SKU和Internal ID,不要删除原SKU代码,将上述代码添加到原代码之后即可。
内容的提问来源于stack exchange,提问作者Liam_Cav
相关产品推荐
相关产品推荐

