| 1 |
<?php |
| 2 |
namespace Depicter\Modules\WooCommerce; |
| 3 |
|
| 4 |
use Averta\Core\Utility\Arr; |
| 5 |
|
| 6 |
class Module { |
| 7 |
|
| 8 |
/** |
| 9 |
* Add product to cart |
| 10 |
* @throws \Exception |
| 11 |
*/ |
| 12 |
public function addToCart( $product_id, $args = [] ) { |
| 13 |
if ( ! function_exists('wc_get_product') ) { |
| 14 |
throw new \Exception( __( 'WooCommerce is not installed.', 'depicter' ) ); |
| 15 |
} |
| 16 |
|
| 17 |
$defaults = [ |
| 18 |
'product_sku' => "", |
| 19 |
'quantity' => 1, |
| 20 |
]; |
| 21 |
$args = Arr::merge( $args, $defaults ); |
| 22 |
|
| 23 |
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', $product_id ); |
| 24 |
$product = wc_get_product( $product_id ); |
| 25 |
$quantity = empty( $args['quantity'] ) ? 1 : wc_stock_amount( wp_unslash( $args['quantity'] ) ); |
| 26 |
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity ); |
| 27 |
$product_status = get_post_status( $product_id ); |
| 28 |
$variation_id = 0; |
| 29 |
$variation = []; |
| 30 |
|
| 31 |
if ( $product && 'variation' === $product->get_type() ) { |
| 32 |
$variation_id = $product_id; |
| 33 |
$product_id = $product->get_parent_id(); |
| 34 |
$variation = $product->get_variation_attributes(); |
| 35 |
} |
| 36 |
|
| 37 |
if ( $passed_validation && false !== WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation ) && 'publish' === $product_status ) { |
| 38 |
|
| 39 |
do_action( 'woocommerce_ajax_added_to_cart', $product_id ); |
| 40 |
|
| 41 |
ob_start(); |
| 42 |
|
| 43 |
woocommerce_mini_cart(); |
| 44 |
|
| 45 |
$mini_cart = ob_get_clean(); |
| 46 |
|
| 47 |
$data = [ |
| 48 |
'fragments' => apply_filters( |
| 49 |
'woocommerce_add_to_cart_fragments', |
| 50 |
[ |
| 51 |
'div.widget_shopping_cart_content' => '<div class="widget_shopping_cart_content">' . $mini_cart . '</div>', |
| 52 |
] |
| 53 |
), |
| 54 |
'cart_hash' => WC()->cart->get_cart_hash(), |
| 55 |
]; |
| 56 |
|
| 57 |
} else { |
| 58 |
|
| 59 |
// If there was an error adding to the cart, redirect to the product page to show any errors. |
| 60 |
$data = [ |
| 61 |
'error' => true, |
| 62 |
'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ), |
| 63 |
]; |
| 64 |
} |
| 65 |
|
| 66 |
return $data; |
| 67 |
} |
| 68 |
} |
| 69 |
|