如何检查可变产品 ID 是否在 woocommerce 购物车中?

所以我在 php 中写了这个过于复杂的代码(因为我几天前才开始使用 php),当某些产品在购物车中时,它应该简单地在结帐页面上添加一个自定义复选框,但由于某种原因它只适用于简单的产品我需要它用于可变产品。我试过使用变体 ID 和产品 ID。你能告诉我哪里错了吗?


add_action( 'woocommerce_review_order_before_submit', 'webroom_check_if_product_in_cart' );

function webroom_check_if_product_in_cart() {

    $product_id1 = 9145; // CHANGE THIS WITH YOUR PRODUCT ID 9145      scratch-8974

    $product_id2 = 9151; // CHANGE THIS WITH YOUR PRODUCT ID

    $product_id3 = 9152; // CHANGE THIS WITH YOUR PRODUCT ID

    $product_id4 = 9153; // CHANGE THIS WITH YOUR PRODUCT ID

    $product_id5 = 9155; // CHANGE THIS WITH YOUR PRODUCT ID

    $product_id6 = 9156; // CHANGE THIS WITH YOUR PRODUCT ID

    $product_cart_id1 = WC()->cart->generate_cart_id( $product_id1 );

    $product_cart_id2 = WC()->cart->generate_cart_id( $product_id2 );

    $product_cart_id3 = WC()->cart->generate_cart_id( $product_id3 );

    $product_cart_id4 = WC()->cart->generate_cart_id( $product_id4 );

    $product_cart_id5 = WC()->cart->generate_cart_id( $product_id5 );

    $product_cart_id6 = WC()->cart->generate_cart_id( $product_id6 );

    $in_cart1 = WC()->cart->find_product_in_cart( $product_cart_id1 );

    $in_cart2 = WC()->cart->find_product_in_cart( $product_cart_id2 );

    $in_cart3 = WC()->cart->find_product_in_cart( $product_cart_id3 );

    $in_cart4 = WC()->cart->find_product_in_cart( $product_cart_id4 );

    $in_cart5 = WC()->cart->find_product_in_cart( $product_cart_id5 );

    $in_cart6 = WC()->cart->find_product_in_cart( $product_cart_id6 );

    if ( $in_cart1 || $in_cart2 || $in_cart3 || $in_cart4 || $in_cart5 || $in_cart6) { 

       echo add_my_checkout_tickbox();

   }

}



慕森卡
浏览 281回答 1
1回答

RISEBY

这是代码的最终版本,在阅读了上面“7uc1f3r”提供的参考资料之后。谢谢您的帮助。add_action( 'woocommerce_review_order_before_submit', 'add_custom_checkbox' );function add_custom_checkbox() {    ## ----- CHECK IF CERTAIN PRODUCTS (COULD ALSO BE VARIABLE PRODUCTS) ARE IN CART ----- ##    $product_ids = array (9145, 9151, 9152, 9153, 9155, 9156); // Search for this products (PARENT ID)    // Loop though cart items searching for the defined products    foreach( WC()->cart->get_cart() as $cart_item ) {        // Product id        $product_id = $cart_item['product_id'];        // Display checkbox if product found in cart        if ( in_array( $product_id, $product_ids) ) {            echo add_my_checkout_tickbox();        }    }}
打开App,查看更多内容
随时随地看视频慕课网APP