WordPress中统计WooCommerce产品高级自定义字段总数值失败如何解决
排查与解决步骤
- 确认自定义字段调用方式
get_field()是Advanced Custom Fields(ACF)插件的专属方法,如果你没有使用ACF创建自定义字段,该函数无法正常读取数值,需要替换为WordPress原生的get_post_meta()方法,调用格式为get_post_meta( 产品ID, '字段键名', true )。 - 确认字段返回值类型
部分场景下自定义字段返回的是字符串格式,累加前需要强制转为数值类型,避免类型转换失败导致计算结果为0。 - 补充产品查询条件
WooCommerce产品存在多个状态,需要明确指定post_status参数查询已发布产品;如果你的自定义字段是绑定在可变产品的子变体上,还需要将post_type增加product_variation类型,否则无法读取变体的字段值。 - 核对字段键名
可进入单个产品编辑页的自定义字段面板,确认你创建的字段键名确实为n_totale,避免拼写、大小写错误导致无法读取字段值。
修正后可直接使用的代码
<?php $pair_total = 0; $posts = get_posts(array( 'posts_per_page' => -1, 'post_type' => array('product', 'product_variation'), // 不需要统计变体可删除product_variation 'post_status' => 'publish' // 仅统计已上架产品 )); if( $posts ) { foreach( $posts as $post ){ setup_postdata( $post ); // 兼容原生自定义字段和ACF的写法 $current_val = get_post_meta( $post->ID, 'n_totale', true ); if ( !empty($current_val) && is_numeric($current_val) ) { $pair_total += intval($current_val); // 字段值为小数的话换成floatval } } wp_reset_postdata(); } ?> <h1><?php echo $pair_total; ?></h1>
内容的提问来源于stack exchange,提问作者Giosuè Gherardi
相关产品推荐
相关产品推荐

