| 1 |
<?php |
| 2 |
|
| 3 |
namespace StoreEngine\Shortcode; |
| 4 |
|
| 5 |
if ( ! defined( 'ABSPATH' ) ) { |
| 6 |
exit; |
| 7 |
} |
| 8 |
|
| 9 |
use StoreEngine\Utils\Formatting; |
| 10 |
use StoreEngine\Utils\Helper; |
| 11 |
use StoreEngine\Utils\Template; |
| 12 |
|
| 13 |
class AddToCart { |
| 14 |
public function __construct() { |
| 15 |
add_shortcode( 'storeengine_add_to_cart', array( $this, 'render' ) ); |
| 16 |
} |
| 17 |
|
| 18 |
public function render( array $attrs ) { |
| 19 |
$attrs = shortcode_atts( [ |
| 20 |
'label' => '', |
| 21 |
'product_id' => null, |
| 22 |
'price_id' => null, |
| 23 |
'variation_id' => 0, |
| 24 |
'direct_checkout' => 'true', |
| 25 |
'quantity' => 1, |
| 26 |
'show_quantity' => 'false', |
| 27 |
'disabled' => 'false', |
| 28 |
'price_display' => 'radio', |
| 29 |
'button_display' => 'yes', |
| 30 |
'dummy' => false, |
| 31 |
'icon' => '', |
| 32 |
'icon_position' => 'left', |
| 33 |
], $attrs ); |
| 34 |
|
| 35 |
if ( empty( $attrs['product_id'] ) ) { |
| 36 |
return __( 'Product ID is required', 'storeengine' ); |
| 37 |
} |
| 38 |
|
| 39 |
if ( $attrs['variation_id'] ) { |
| 40 |
$variation = Helper::get_product_variation( (int) $attrs['variation_id'] ); |
| 41 |
if ( ! $variation ) { |
| 42 |
return __( 'Variation not found', 'storeengine' ); |
| 43 |
} |
| 44 |
$attrs['variation_id'] = $variation->get_id(); |
| 45 |
} |
| 46 |
|
| 47 |
$product_id = (int) $attrs['product_id']; |
| 48 |
$product = Helper::get_product( $product_id ); |
| 49 |
if ( ! $product ) { |
| 50 |
return __( 'Product not found', 'storeengine' ); |
| 51 |
} |
| 52 |
|
| 53 |
$label = $attrs['label']; |
| 54 |
$direct_checkout = Formatting::string_to_bool( $attrs['direct_checkout'] ); |
| 55 |
if ( empty( $label ) ) { |
| 56 |
if ( $direct_checkout ) { |
| 57 |
$label = __( 'Buy now', 'storeengine' ); |
| 58 |
} else { |
| 59 |
$label = __( 'Add to cart', 'storeengine' ); |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
$price_id = $attrs['price_id']; |
| 64 |
$prices = $product->get_prices(); |
| 65 |
if ( 1 === count( $prices ) ) { |
| 66 |
$price_id = $prices[0]->get_id(); |
| 67 |
} |
| 68 |
|
| 69 |
return Template::get_template_content( 'shortcode/add-to-cart.php', [ |
| 70 |
'product' => $product, |
| 71 |
'price_id' => $price_id, |
| 72 |
'variation_id' => $attrs['variation_id'], |
| 73 |
'direct_checkout' => $direct_checkout, |
| 74 |
'quantity' => $attrs['quantity'], |
| 75 |
'show_quantity' => Formatting::string_to_bool( $attrs['show_quantity'] ), |
| 76 |
'disabled' => Formatting::string_to_bool( $attrs['disabled'] ), |
| 77 |
'label' => $label, |
| 78 |
'prices' => $prices, |
| 79 |
'price_display' => $attrs['price_display'], |
| 80 |
'dummy' => $attrs['dummy'], |
| 81 |
'icon' => $attrs['icon'], |
| 82 |
'icon_position' => $attrs['icon_position'], |
| 83 |
'button_display' => Formatting::string_to_bool( $attrs['button_display'] ), |
| 84 |
] ); |
| 85 |
} |
| 86 |
} |
| 87 |
|