WooCommerce结账页显示属性名称而非Slug的实现求助
问题
我的网站测试地址为:https://prebuild.nesmrtelnost.tw/。在结账页面(https://prebuild.nesmrtelnost.tw/checkout/)的「您的订单」区域,目前显示产品名称、变体属性Slug、数量及价格。我希望将变体属性Slug替换为属性名称,但已通过Snippets插件添加的PHP代码未生效,怀疑是SellKit插件修改了woocommerce_order_item_meta相关钩子导致,请问该如何调整?
我添加的代码如下:
/** * Showing attributes name instead of slug in ckeckout page */ function replace_variation_slug_with_name_in_checkout($display_value, $meta, $item) { $taxonomy_prefix = 'pa_'; if (strpos($meta->key, $taxonomy_prefix) === 0) { $taxonomy = substr($meta->key, strlen($taxonomy_prefix)); if (taxonomy_exists($taxonomy)) { $term = get_term_by('slug', $meta->value, $taxonomy); if ($term && !is_wp_error($term)) { return $term->name; } } } return $display_value; }
解决方案
1. 补全钩子绑定并提高优先级
你的代码逻辑本身没问题,但可能因为SellKit插件的钩子优先级更高,覆盖了你的修改。只需为函数绑定正确的钩子并提高优先级即可:
/** * 替换结账页面变体属性Slug为属性名称 */ function replace_variation_slug_with_name_in_checkout($display_value, $meta, $item) { $taxonomy_prefix = 'pa_'; if (strpos($meta->key, $taxonomy_prefix) === 0) { $taxonomy = substr($meta->key, strlen($taxonomy_prefix)); if (taxonomy_exists($taxonomy)) { $term = get_term_by('slug', $meta->value, $taxonomy); if ($term && !is_wp_error($term)) { return $term->name; } } } return $display_value; } // 提高优先级至20,确保在SellKit的钩子之后执行 add_filter('woocommerce_order_item_display_meta_value', 'replace_variation_slug_with_name_in_checkout', 20, 3);
2. 尝试替代钩子
如果上述方法无效,可改用woocommerce_get_item_data钩子,这个钩子负责渲染购物车及结账页的项目元数据,SellKit通常不会完全替换这个钩子:
/** * 替换结账页面变体属性Slug为属性名称 */ function replace_variation_slug_with_name_in_checkout_item_data($item_data, $cart_item) { foreach ($item_data as $key => $data) { $taxonomy_prefix = 'pa_'; if (strpos($data['key'], $taxonomy_prefix) === 0) { $taxonomy = substr($data['key'], strlen($taxonomy_prefix)); $term = get_term_by('slug', $data['value'], $taxonomy); if ($term && !is_wp_error($term)) { $item_data[$key]['value'] = $term->name; } } } return $item_data; } add_filter('woocommerce_get_item_data', 'replace_variation_slug_with_name_in_checkout_item_data', 20, 2);
3. 针对SellKit自定义钩子调整
如果前两种方法都无效,说明SellKit使用了自定义钩子来渲染结账订单元数据。你可以通过以下步骤排查:
- 找到SellKit插件的结账模板文件(通常位于
wp-content/plugins/sellkit/templates/checkout/目录下) - 查找渲染订单项目元数据的代码,定位它使用的自定义钩子(例如
sellkit_order_item_meta_display_value) - 将你的函数绑定到该钩子上,优先级设为20或更高
内容的提问来源于stack exchange,提问作者Nesmrtelnost
相关产品推荐
相关产品推荐

