PHP8.1下WooCommerce upsells_total返回非整数致致命错误求助
错误详情
从PHP7.4升级至PHP8.1后,访问商品页面触发致命错误:
Fatal error: Uncaught TypeError: array_slice(): Argument #3 ($length) must be of type ?int, array given in F:\Websites\rewave\wp-content\plugins\woocommerce\includes\wc-template-functions.php:2087 Stack trace: #0 F:\Websites\rewave\wp-content\plugins\woocommerce\includes\wc-template-functions.php(2087): array_slice(Array, 0, Array) #1 F:\Websites\rewave\wp-includes\class-wp-hook.php(307): woocommerce_upsell_display(Array) #2 F:\Websites\rewave\wp-includes\class-wp-hook.php(331)
问题根源是woocommerce_upsells_total过滤器返回了数组而非整数,导致array_slice函数参数类型不匹配。直接修改WooCommerce核心文件可临时修复,但需寻求无需修改核心文件的替代方案。
环境与代码信息
主题详情
- 基于Timber & Twig开发
- WooCommerce版本7.0.0
- PHP版本8.1
当前模板PHP代码
/* Single product */ $context['post'] = Timber::get_post(); $product = wc_get_product( $context['post']->ID ); $context['product'] = $product; // Get related products $related_limit = wc_get_loop_prop( 'columns' ); $related_ids = wc_get_related_products( $context['post']->id, $related_limit ); $context['related_products'] = Timber::get_posts( $related_ids ); // Restore the context and loop back to the main query loop. wp_reset_postdata(); Timber::render( 'templates/woocommerce/product.twig', $context );
已尝试方案
- 手动更新WooCommerce
- 移除PHP文件中除获取文章外的所有内容(仍报错)
- 尝试覆写
woocommerce_upsell_display函数
非核心修改解决方案
无需修改WooCommerce核心文件,只需在主题的functions.php中添加以下代码,通过钩子修正woocommerce_upsells_total过滤器的返回值类型:
add_filter( 'woocommerce_upsells_total', 'fix_woocommerce_upsells_total_type', 10, 1 ); function fix_woocommerce_upsells_total_type( $limit ) { // 强制转换为整数,若转换失败则设为默认值(可根据需求调整) return is_numeric( $limit ) ? (int) $limit : 4; }
这段代码会拦截woocommerce_upsells_total过滤器的返回值,确保最终返回整数类型,避免array_slice触发类型错误。
内容的提问来源于stack exchange,提问作者Michael W.

