I am looking to add a selection of products to some of our single product pages.
I have added a select field that is grabbing all of the products of a specific category and adding them as options.
Based on the users selection, I would like to add the selected product to the cart along with the main product. This only if the additional product is not yet in the cart.
Here is my code attempt:
function comp_bracket_selection( $selection ) {
echo '<div><br></div>';
global $product;
$domain = 'woocommerce';
$args = array(
'category' => 'compressor-brackets',
'limit' => -1,
);
$product_array = wc_get_products( $args );
foreach ($product_array as $comp_product) {
$comp_id = $comp_product->get_id();
echo 'Product id: ' . $comp_id . ' | ';
$options[$comp_id] = $comp_product->get_name();
}
array_unshift($options, 'Choose an option');
woocommerce_form_field('compressor-options', array(
'id' => 'compressor-selection',
'type' => 'select',
'label' => __('Choose Compressor & Bracket', $domain),
'required' => false,
'options' => $options,
),''
);
echo '<p>Number of Compressor & Bracket options: ' . sizeof( $product_array ) . '</p>';
}
add_action( 'woocommerce_before_add_to_cart_button', 'comp_bracket_selection' );
function custom_add_to_cart() {
if (isset($_POST['compressor-options'])) {
$product_id = $_POST['compressor-options'];
$found = false;
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
WC()->cart->add_to_cart( $product_id );
}
}
}
add_action( 'woocommerce_add_to_cart', 'custom_add_to_cart' );
But I have issues getting the selected products added to the cart. Any advice would be much appreciated.