WooCommerce:为含Fiat的新建产品添加购买备注元数据
WooCommerce产品自动添加购买备注代码修复
你的代码存在几个直接导致功能失效的问题,修复点如下:
- 变量引用错误:
wc_get_product( id )中的id未加$符号,且未传入正确的产品标识,应改为wc_get_product( $post )(直接传入post对象更高效)或wc_get_product( $post->ID )。 - 变量名拼写错误:定义的变量是
$prod_name,但判断时误用了$product_name,变量名不匹配导致无法获取正确的产品名称进行字符串匹配。 - strpos判断逻辑错误:strpos函数返回匹配到的索引位置(数字)或false,不能用
=== true判断匹配结果。同时你将产品名称转为小写,但匹配字符串保留大写"Fiat",大小写不统一会导致匹配失败,需将两者统一为相同大小写后再判断。 - 逻辑优化:先判断post类型是否为product,再执行后续操作,减少不必要的资源消耗。
修复后的完整代码:
add_action( 'transition_post_status', 'bbloomer_add_custom_meta_on_publish_product', 9999, 3 ); function bbloomer_add_custom_meta_on_publish_product( $new_status, $old_status, $post ) { // 非产品类型直接返回,避免无效执行 if ( 'product' !== $post->post_type ) return; // 仅在产品首次发布时执行 if ( 'publish' === $new_status && 'publish' !== $old_status ) { $product = wc_get_product( $post ); $prod_name = $product->get_title(); $string_to_find = 'Fiat'; // 统一转小写匹配,忽略大小写差异 if ( strpos( strtolower( $prod_name ), strtolower( $string_to_find ) ) !== false ) { update_post_meta( $post->ID, '_purchase_note', 'This is my Fiat text' ); } } }
内容的提问来源于stack exchange,提问作者Rosalito Udtohan
相关产品推荐
相关产品推荐

