WordPress中根据产品ID添加自定义文本$text的代码实现求助
问题分析与解决方案
你的核心问题在于条件判断的逻辑写法错误,PHP里$product['id'] == ('8499' || '5348'|| '5389' || '7331')这种写法不会按你预期的判断ID是否在指定列表里——因为||逻辑或运算符会先计算括号里的表达式,多个非空字符串做或运算结果永远是true,最终变成$product['id'] == true,所有非零的产品ID都会匹配这个条件,完全不符合你的需求。
正确的实现方式
我们可以用in_array()函数来判断产品ID是否在目标数组中,这种写法既简洁又符合PHP的语法逻辑。另外记得提前初始化$text变量,避免出现未定义的警告。
修改后的完整脚本
require('../wp-load.php'); header("Pragma: no-cache"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Expires: 0"); $access = false; if(isset($_SESSION['stock_control_access'])){ if($_SESSION['stock_control_access'] == "yes"){ $access = true; } } if($access == false){ exit("accessdenied"); } if(!isset($_GET['item_id'])){ exit("Mauvaise requête"); } $cat_id = $_GET['item_id']; wp_set_current_user(null, "user"); $request = new WP_REST_Request('GET', "/wc/v3/products"); $request->set_query_params(["per_page" => "100", "category" => $cat_id]); $response = rest_do_request($request); $server = rest_get_server(); $products = $server->response_to_data($response, false); $output = ''; $output .= "<ul class='product_list' id='{$cat_id}'>" . PHP_EOL; foreach ($products as $product) { // 初始化text变量,避免未定义警告 $text = ''; $product_id = $product['id']; // 判断ID是否在目标组1中 if(in_array($product_id, [8499, 5348, 5389, 7331])) { $text = "test1"; } // 判断ID是否在目标组2中 if(in_array($product_id, [8494, 5368, 5339, 5331])) { $text = "test2"; } if($product['type'] == 'simple'){ $output .= "<li class='product' data-id='{$product['id']}' data-type='simple' data-stock='{$product['stock_quantity']}' data-open='closed'><a href='{$product['images'][0]['src']}' target='_blank'><img src='{$product['images'][0]['src']}'></a>{$product['name']}-{$product['id']} {$text}</li>"; } else { $output .= "<li class='product' data-id='{$product['id']}' data-open='closed'><a href='{$product['images'][0]['src']}' target='_blank'><img src='{$product['images'][0]['src']}'></a>{$product['name']}-{$product['id']}</li>"; } $output .= PHP_EOL; } $output .= '</ul>'; echo $output; ?>
额外说明
- 产品ID在WooCommerce里是整数类型,所以我们直接用数字数组(
[8499, 5348,...])而不是字符串数组,判断更准确;如果你的ID是字符串格式,把数组里的数字改成带引号的字符串即可。 - 提前初始化
$text = '',这样即使产品ID不在任何目标组里,也不会出现变量未定义的PHP警告。 - 如果需要添加更多分组的自定义文本,直接新增
in_array判断即可,扩展性很强。
内容的提问来源于stack exchange,提问作者Solution Manutention
相关产品推荐
相关产品推荐

