1

i'm trying to compare array1_ids with the cart of a customer if products of the array match those in the cart field x_name should be there if not it should be gone. I get the values from my cart and array1_ids but when I put them through the array_intersect it will result in NULL causing it to always return true.

Here is my code:

function wc_ninja_product_is_in_the_cart() {
/*array 1*/
$array1_ids = array( '1', '3', '5');//field that should
/*array 2*/
//$micro_ids = array( '2', '4');//fields that shouldnt come back

    // Products currently in the cart
    $cart_ids = array();
    $cart_categories = array();

    // Find each product in the cart and add it to the $cart_ids array
    foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
        $cart_product = $values['data'];
        $cart_ids[]   = $cart_product->id;
    }

    // If one of the special products are in the cart, return true.
    if ( ! array_intersect($array1_ids, $cart_ids) ) {
        echo "true: " , implode(';',$cart_ids);;//bug fixing
        return true;
    } else {
        return false;
        echo "false: " , implode(';',$cart_ids);;//bug fixing
    }
}
//Field Remover
function wc_ninja_remove_checkout_field( $fields ) {
    if ( ! wc_ninja_product_is_in_the_cart() )    {
        //removes Field x_name
        unset( $fields['billing']['x_name'] );
    }
    return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'wc_ninja_remove_checkout_field' ); 
2
  • Are you sure $card_ids has elements?
    – Jerodev
    Dec 23, 2016 at 15:10
  • everything returns values unless you run them through the array_intersect() Dec 23, 2016 at 15:13

1 Answer 1

1

This should work:

$hasSpecialProduct= false;    
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
    $cart_product = $values['data'];
    if (in_array($cart_product->id, $array1_ids)) {
        $hasSpecialProduct = true;
    }
    $cart_ids[]   = $cart_product->id;
}

// If one of the special products are in the cart, return true.
if ( $hasSpecialProduct ) {
    echo "true: " , implode(';',$cart_ids);;//bug fixing
    return true;
} else {
    return false;
}

you can make the last part shorter:

return $hasSpecialProduct;
1
  • 1
    Thank you very much this worked! I can not upvote since I am new on stack overflow but thanks anyway. I've accepted your answer anyway. Dec 23, 2016 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.