0

I've got these functions which check product ids in cart but i need to check it against an array of product ids added to a form using the variable $products_ids.

Update 2 : This is the default var_dump for both arrays :

$products_ids as follows

array (size=2)
  0 => int 111342
  1 => int 111347

and $cart_ids

array (size=3)
  'e877cbddd23b3bfa5b77782ba905b32e' => int 111347
  '696d28043ad274014f653ca2d9a64812' => int 111342
  '4363f14c8e54babb17770c2b4980ceed' => int 14535

And this is the new code i am trying :

function matched_ids() {

    $cart_ids = array_merge(
        wp_list_pluck(WC()->cart->get_cart_contents(), 'variation_id'),
        wp_list_pluck(WC()->cart->get_cart_contents(), 'product_id')
    );

    $product_ids  = get_option('restricted_product_ids');
    
    $ids          =   array_map('intval', explode( ',',  $product_ids ) );
    
    return array_intersect( $ids, $cart_ids );
    
}

But it returns Array when i need it to check the $products_ids array against the $cart_ids array to find matched ids and output the matched_ids() function on the frontend to display matched string of product ids.

2
  • Please give an example of the value of restricted_product_ids. Is it an array of ID's [1, 2, 3]? Is it a comma separated string of ID's '1,2,3'? Is it just a single ID 1? Commented Mar 22, 2023 at 16:13
  • 1
    $product_ids outputs string '111342, 111347' Commented Mar 22, 2023 at 16:41

1 Answer 1

0

This should do the trick...

// Convert comma separated string of ids into an array if integers.
$restricted_product_ids = array_filter( array_map( 'absint', explode( ',', get_option( 'restricted_product_ids' ) ) ) );

// Our output array.
$ids = [];

// Loop through each item in the cart.
foreach( WC()->cart->get_cart() as $cart_item ) {

    // Get the product id.
    $product_id = absint( $cart_item[ 'product_id' ] );

    // Check if the product id is restricted.
    if ( in_array( $product_id, $restricted_product_ids ) ) {

        // Add it to our output array.
        $ids[] = $product_id;
    }
}

// Make array of id's a comma separated string.
$matched_ids = implode( ', ', $ids );

We get all the items in the cart and loop through them. Inside the loop we have access to each of the items product ID's. With the product ID we can then check if it exists in the restricted array and then push it to our output.

Sign up to request clarification or add additional context in comments.

11 Comments

Thanks but i get Parse error: syntax error, unexpected '}', expecting ';'
@BrettStack1 I've fixed the parse error. Try that and let me know
How do i use it to get the ids. I need to output the matched ids in the frontend.
If you read the code you’ll see that it is building an array of matched IDs in the $ids variable. You can then use that to do whatever you need to.
Internal Server Error returns Array.. See updated question.
|