WooCommerce订阅页面无法显示SLM许可证?修改钩子后无效果求排查
问题原因与解决方案
问题出在这几个关键点:
条件判断逻辑不兼容订阅对象
原代码里的wcs_order_contains_subscription( $order, 'parent' )是用来判断「普通订单是否是包含订阅的父订单」,但woocommerce_subscription_totals_table钩子传入的是WC_Subscription(订阅)对象,不是父订单,这个条件会直接返回false,导致后续获取许可证的逻辑根本不会执行。许可证数据不在订阅对象里
Software License Manager的许可证是绑定在父订单的订单项元数据中,而不是订阅对象的订单项里。直接遍历订阅的订单项,自然找不到_slm_lic_key和_slm_lic_type这些元数据。状态判断逻辑错误
订阅的状态通常是active/on-hold这类,不会是completed;但生成许可证的父订单状态才是completed。原代码直接判断传入对象的状态为completed,订阅对象肯定不满足这个条件。
修改后的代码
把原函数改成下面这样,就能在订阅页面正确显示许可证:
/** * Display license details on subscription view page */ function slm_subscription_details($subscription) { // 从订阅获取对应的父订单 $parent_order = $subscription->get_parent(); if ( !$parent_order || !$parent_order->has_status('completed') ) { return; // 父订单不存在或未完成,直接退出 } global $wpdb; $items = $parent_order->get_items(); $licences = array(); foreach ($items as $item_key => $item_details) { $product = $item_details->get_product(); // 只处理订阅类型的产品 if ( $product->is_type('subscription') ) { if ($lic_keys = wc_get_order_item_meta($item_details->get_id(), '_slm_lic_key', false)) { $lic_types = wc_get_order_item_meta($item_details->get_id(), '_slm_lic_type', false); $licences = array_map(function ($keys, $types) { return array( 'lic_key' => $keys, 'lic_type' => $types ); }, $lic_keys, $lic_types); } } } if ($licences) { echo ' <h2 class="woocommerce-order-details__title">' . __('License details', 'softwarelicensemanager') . '</h2> <table class="woocommerce-table woocommerce-table--order-details shop_table order_details"> <thead> <tr> <th class="woocommerce-table__product-name product-name">' . __('License key', 'softwarelicensemanager') . '</th> <th class="woocommerce-table__product-table product-total">' . __('Type', 'softwarelicensemanager') . '</th> </tr> </thead> <tbody> '; foreach ($licences as $lic_row) { echo ' <tr class="woocommerce-table__line-item order_item"> <td class="woocommerce-table__product-name product-name"> ' . $lic_row['lic_key'] . ' - <a href="' . get_permalink(wc_get_page_id('myaccount')) . '/my-licenses"> ' . __('view my licenses', 'softwarelicensemanager') . '</a> </td> <td class="woocommerce-table__product-total product-total"> ' . $lic_row['lic_type'] . ' </td> </tr> '; } echo ' </tbody> </table> '; } } add_action('woocommerce_subscription_totals_table', 'slm_subscription_details', 10, 1);
代码改动说明:
- 获取父订单:通过
$subscription->get_parent()拿到生成订阅的原始父订单,许可证数据存在这里。 - 调整状态判断:只检查父订单是否为
completed状态,忽略订阅本身的状态。 - 简化产品类型判断:去掉了原代码里的
wcs_order_contains_subscription判断,因为父订单里的订阅产品已经满足条件。 - 保持原有渲染逻辑:许可证的HTML渲染部分和原代码一致,确保样式和订单页统一。
内容的提问来源于stack exchange,提问作者social.reza
相关产品推荐
相关产品推荐

