【问题标题】:WooCommerce if condition (if product is in cart do something)WooCommerce 如果条件(如果产品在购物车中做某事)
【发布时间】:2018-09-30 17:40:05
【问题描述】:

我试图在 WooCommerce 购物车页面上显示附加按钮 [预约您的预约],该按钮会将用户带到带有预约产品的页面。这部分工作得很好。我还尝试检查产品 ID 444908 是否已在购物车中。产品 ID 444908 是预约产品,如果某人已经预约了预约,则不应显示该按钮,因为该人已经在购物车中预订了产品。 似乎问题出在我的 IF 条件上。当我使用它时,无论产品 444908 是否在购物车中,它都不会显示按钮。

我做错了什么?

add_action( 'woocommerce_after_cart_totals', 'my_continue_shopping_button' );
function my_continue_shopping_button() {
    $product_id = 444908;
    $product_cart_id = WC()->cart->generate_cart_id( $product_id );
    $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
    if ( $in_cart ) {
 echo '<div class="bookbtn"><br/>';
 echo ' <a href="/book-appointment/" class="button"><i class="fas fa-calendar-alt"></i> Book Your Appointment</a>';
 echo '</div>';
 }
}

【问题讨论】:

    标签: php wordpress woocommerce cart product


    【解决方案1】:

    最后我使用了外部函数:

    function woo_is_in_cart($product_id) {
        global $woocommerce;
        foreach($woocommerce->cart->get_cart() as $key => $val ) {
            $_product = $val['data'];
            if($product_id == $_product->get_id() ) {
                return true;
            }
        }
        return false;
    }
    

    然后我使用这个检查产品是否在购物车中:

    if(woo_is_in_cart(5555) !=1) {
    /* where 5555 is product ID */
    

    【讨论】:

    • 按照 LoicTheAztec 的建议编辑
    • 我已经稍微更新了你的代码,让它变得真实而紧凑……
    • 奇怪它应该……我已经回滚了
    【解决方案2】:

    find_product_in_cart 如果未找到产品,则返回空字符串 所以你需要

     if ( $in_cart !="" ) 
    

    info

    【讨论】:

      【解决方案3】:

      这是我已经使用了一段时间的东西?

      function is_in_cart( $ids ) {
          // Initialise
          $found = false;
      
          // Loop through cart items
          foreach( WC()->cart->get_cart() as $cart_item ) {
              // For an array of product IDs
              if( is_array($ids) && ( in_array( $cart_item['product_id'], $ids ) || in_array( $cart_item['variation_id'], $ids ) ) ){
                  $found = true;
                  break;
              }
              // For a unique product ID (integer or string value)
              elseif( ! is_array($ids) && ( $ids == $cart_item['product_id'] || $ids == $cart_item['variation_id'] ) ){
                  $found = true;
                  break;
              }
          }
      
          return $found;
      }
      

      对于单个产品 ID:

      if(is_in_cart($product_id)) {
          // do something
      }
      

      对于产品/变体 ID 数组:

      if(is_in_cart(array(123,456,789))) {
          // do something
      }
      

      ...或...

      if(is_in_cart($product_ids)) {
          // do something
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-18
        • 2020-11-15
        • 2018-09-30
        • 2021-01-31
        • 2019-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多