| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Hooks\Handlers\ShortCodes\Buttons; |
| 4 |
|
| 5 |
use FluentCart\App\Hooks\Handlers\ShortCodes\ShortCode; |
| 6 |
use FluentCart\App\Helpers\Helper; |
| 7 |
use FluentCart\App\Models\Product; |
| 8 |
use FluentCart\App\Models\ProductVariation; |
| 9 |
use FluentCart\App\Modules\Templating\AssetLoader; |
| 10 |
use FluentCart\App\Services\Renderer\ProductRenderer; |
| 11 |
use FluentCart\Framework\Support\Arr; |
| 12 |
|
| 13 |
class AddToCartShortcode extends ShortCode |
| 14 |
{ |
| 15 |
protected static string $shortCodeName = 'fluent_cart_add_to_cart_button'; |
| 16 |
|
| 17 |
public function getStyles(): array |
| 18 |
{ |
| 19 |
return [ |
| 20 |
'public/buttons/add-to-cart/style/style.scss', |
| 21 |
]; |
| 22 |
} |
| 23 |
|
| 24 |
/** |
| 25 |
* Example: |
| 26 |
* [fluent_cart_add_to_cart_button |
| 27 |
* button_text="Add to Cart" |
| 28 |
* variation_id="123" |
| 29 |
* ] |
| 30 |
* |
| 31 |
* Supported attributes: |
| 32 |
* - button_text |
| 33 |
* - variation_id |
| 34 |
*/ |
| 35 |
public function render(?array $viewData = null) |
| 36 |
{ |
| 37 |
$data = $viewData ?? $this->shortCodeAttributes ?? []; |
| 38 |
|
| 39 |
$buttonText = Arr::get($data, 'button_text', __('Add to Cart', 'fluent-cart')); |
| 40 |
$buttonClass = trim(Arr::get($data, 'class', '')); |
| 41 |
$variationId = (int) Arr::get($data, 'variation_id', 0); |
| 42 |
|
| 43 |
if (!$variationId) { |
| 44 |
return ''; |
| 45 |
} |
| 46 |
|
| 47 |
AssetLoader::loadSingleProductAssets(); |
| 48 |
|
| 49 |
$rendererConfig = []; |
| 50 |
$product = null; |
| 51 |
|
| 52 |
// 1) Try treating variation_id as the actual variation primary ID |
| 53 |
$variant = ProductVariation::query()->find($variationId); |
| 54 |
|
| 55 |
// 2) Fallback: treat variation_id as variation post_id |
| 56 |
if (!$variant) { |
| 57 |
$variant = ProductVariation::query() |
| 58 |
->where('post_id', $variationId) |
| 59 |
->first(); |
| 60 |
} |
| 61 |
|
| 62 |
if ($variant) { |
| 63 |
/** @var Product|null $product */ |
| 64 |
$product = Product::query()->find($variant->post_id); |
| 65 |
|
| 66 |
if ($product) { |
| 67 |
$rendererConfig['default_variation_id'] = $variant->id; |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
if (!$product) { |
| 72 |
if (Helper::isAdminUser()) { |
| 73 |
return '<p class="fct-admin-notice">' . esc_html__('Invalid product/variant for Add to Cart button shortcode.', 'fluent-cart') . '</p>'; |
| 74 |
} |
| 75 |
|
| 76 |
return ''; |
| 77 |
} |
| 78 |
|
| 79 |
$atts = [ |
| 80 |
'add_to_cart_text' => $buttonText, |
| 81 |
'is_shortcode' => true, |
| 82 |
]; |
| 83 |
|
| 84 |
if ($buttonClass) { |
| 85 |
$atts['class'] = $buttonClass; |
| 86 |
} |
| 87 |
|
| 88 |
return (new ProductRenderer($product, $rendererConfig))->renderAddToCartButton($atts); |
| 89 |
} |
| 90 |
} |
| 91 |
|