如何为未加入购物车的商品ID添加WooCommerce购物车提示
问题解答
你完全可以通过**逻辑非运算符!**来实现需求,根本不需要用到elseif。你最终更新后的代码已经做了正确的处理——if ( ! $in_cart )就是精准判断指定商品未在购物车时的逻辑分支,直接执行提示即可,逻辑清晰又简洁。
关键逻辑说明
WC()->cart->find_product_in_cart()方法:当商品在购物车中时,会返回对应的购物车条目;不存在时则返回false! $in_cart直接对结果取反,刚好满足“商品不在购物车时显示提示”的需求,不需要额外的elseif分支
修正后的完整代码
add_action( 'woocommerce_before_cart', 'print_custom_cart_notice', 10 ); function print_custom_cart_notice() { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; $user_obj = wp_get_current_user(); if ( in_array('customer', $user_obj->roles ) || ! is_user_logged_in() ) { $link = 'https://website.com/cart/?add-to-cart=13720&quantity=1'; $product_id = 13720; $product_cart_id = WC()->cart->generate_cart_id( $product_id ); $in_cart = WC()->cart->find_product_in_cart( $product_cart_id ); if ( ! $in_cart ) { wc_print_notice( sprintf( '<span class="cross-sell-cart">' . __('Add a Tote Bag to your order. %s', 'woocommerce') . '</span>', '<a href='.$link.' class="button alt" style="float:right">'. __('Add to Cart', 'woocommerce') .'</a>' ), 'notice' ); } } }
内容的提问来源于stack exchange,提问作者Wanderlust Consulting
相关产品推荐
相关产品推荐

