2016-12-05 60 views
0

我在php中爲wordpress創建了一個過濾器,當具有特定裝運類的產品在購物車中時顯示一條特殊消息。特別的信息出現多次,因爲該類別的許多產品都在購物車中。我怎樣才能限制輸出只有一個?下面的代碼:如何限制對一個php過濾器的響應?

add_action('woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12); 
 
function allclean_add_checkout_content() { 
 
    // set your special category name, slug or ID here: 
 
    $shippingclass = array('cut'); 
 
    $bool = false; 
 
    foreach (WC()->cart->get_cart() as $cart_item_key => $values) { 
 
\t $shipping_class = get_the_terms($values['variation_id'], 'product_shipping_class'); 
 

 
     if (isset($shipping_class[0]->slug) && in_array($shipping_class[0]->slug, $shippingclass)) { 
 
      $bool = true; 
 
    } 
 
    // If the special cat is detected in one items of the cart 
 
    // It displays the message 
 
    if ($bool) 
 
     echo '<div class="example1"><h3>Items in your cart can be cut to save on shipping. List which items you want cut in your order notes.</h3></div>'; 
 
} 
 
}

回答

0

你的foreach循環中呼應它。只需將它移到外面。此外,一審被發現後,就沒有必要繼續循環,因此與break打破它,你設置後$booltrue

add_action('woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12); 

function allclean_add_checkout_content() 
{ 
    // set your special category name, slug or ID here: 
    $shippingclass = array('cut'); 
    $bool = false; 
    foreach (WC()->cart->get_cart() as $cart_item_key => $values) 
    { 
     $shipping_class = get_the_terms($values['variation_id'], 'product_shipping_class'); 

     if (isset($shipping_class[0]->slug) && in_array($shipping_class[0]->slug, $shippingclass)) 
     { 
      $bool = true; 
      break; 
     } 
    } 
    // If the special cat is detected in one items of the cart 
    // It displays the message 
    if ($bool) 
    { 
     echo '<div class="example1"><h3>Items in your cart can be cut to save on shipping. List which items you want cut in your order notes.</h3></div>'; 
    } 
}