如何在WooCommerce中检查当前用户是否拥有特定产品的待处理订单并在产品页根据订单状态显示元素?
解决WooCommerce产品页判断用户对应产品pending订单的问题
嘿,我来帮你搞定这个需求!你已经拿到了用户订单和产品ID,接下来只需要过滤出用户针对当前产品的pending状态订单就行,我给你整理了完整的实现代码和思路:
核心思路
- 先确保用户已经登录,避免未登录场景下的错误
- 直接获取用户的pending状态订单(不用遍历所有订单,效率更高)
- 遍历这些订单里的商品,检查是否包含当前产品ID
- 如果找到匹配的订单,就显示你需要的按钮
完整代码实现
把这段代码替换你原来的判断逻辑部分就行:
<?php // 先判断用户是否登录 if (is_user_logged_in()) { $user_id = get_current_user_id(); $product_id = $product->get_id(); $has_pending_order = false; // 获取当前用户所有pending状态的订单,限定状态能减少循环量 $orders = wc_get_orders([ 'customer_id' => $user_id, 'status' => 'pending', // 只拉取pending状态的订单 'limit' => -1, // 获取所有符合条件的订单 ]); // 遍历每个订单,检查是否包含当前产品 foreach ($orders as $order) { foreach ($order->get_items() as $item) { // 用absint确保ID是整数,避免类型不匹配 if (absint($item->get_product_id()) === $product_id) { $has_pending_order = true; break 2; // 找到匹配项后直接跳出两层循环,节省资源 } } } // 如果存在符合条件的订单,显示按钮 if ($has_pending_order) { ?> <a href="<?php echo esc_url(home_url('redirect-to-room/' . $product->get_id())) ?>" class="button alt"> <?php _e('Enter room', 'skyroom') ?> </a> <?php } } ?>
额外注意事项
- 变体产品兼容:如果你的产品有变体,需要额外检查
$item->get_variation_id(),比如把判断条件改成absint($item->get_product_id()) === $product_id || absint($item->get_variation_id()) === $product_id - 安全优化:用
esc_url()处理跳转链接,避免XSS安全问题 - 模板可用性:确保
$product变量在当前模板中是有效的(在WooCommerce的single-product.php页面里默认是可用的)
内容的提问来源于stack exchange,提问作者melk yar
相关产品推荐
相关产品推荐

