I'm doing some customisation to the mini-cart. When a user adds a product to the cart, inside the mini-cart I'm creating a slider containing the added product's cross-sales. So for example, user adds Product A that has cross-sales products X, Y, Z. Once his mini-cart opens he sees a slider with these products and a button to add them to the cart. The problem I'm having is that the add to cart button is not working.. I have enabled ajax add to cart and I'm noticing that only one product is getting url /?wc-ajax=add_to_cart&add-to-cart=productID
, which on click just loads a white screen.. The other products in the slider have urls ?add-to-cart=productID
, which on click just reloads the page and returns empty cart.. So none of the add to cart buttons is working.. In mini-cart.php, I have this code that creates the slider:
$products_cs = array();
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
$the_product = wc_get_product( $cart_item['product_id'] );
$cross_sell_ids = $the_product->get_cross_sell_ids();
$products_cs = array_merge($products_cs, $cross_sell_ids);
$products_cs = array_unique($products_cs);
}
<div class="mini-cart-offers">
<button type="button" class="mini-cart-offers-prev is-disabled"></button>
<div class="mini-cart-offers-slider">
<?php
foreach ( $products_cs as $offer ) :
$offer_product = wc_get_product( $offer );
?>
<div class="product-offer">
<div class="product-offer__thumbnail">
<?php if (has_post_thumbnail($offer_product->get_id())) : ?>
<a href="<?php echo $offer_product->get_permalink(); ?>">
<?php echo $offer_product->get_image($size = 'medium'); ?>
</a>
<?php endif; ?>
</div>
<div class="product-offer__content">
<div class="product-offer__content-title">
<a href="<?php echo $offer_product->get_permalink(); ?>">
<h5><?php echo $offer_product->get_name(); ?></h5>
</a>
</div>
<div class="product-offer__content-price">
<?php echo $offer_product->get_price_html(); ?>
</div>
<div class="product-offer__content-button">
<a href="<?php echo $offer_product->add_to_cart_url(); ?>" class="button" data-quantity="1" data-product_id="<?php echo $offer; ?>" data-product_sku="<?php echo $offer_product->get_sku(); ?>"><?php _e('Add', 'woocommerce'); ?></a>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<button type="button" class="mini-cart-offers-next"></button>
</div>
Also, I have this slider as a function, which is attached to woocommerce_add_to_cart_fragments
:
add_filter( 'woocommerce_add_to_cart_fragments', 'cart_fragments', 10, 1 );
function cart_fragments( $fragments ) {
if (! WC()->cart->is_empty()) {
ob_start();
mini_cart_slider();
$fragments['div.widget_shopping_cart_content'] .= ob_end_clean();
return $fragments;
} else {
return $fragments;
}
}
How to make the add to cart button work? Preferably it would be to add the product without a page refresh..