PluginProbe
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler / 1.3.21
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler v1.3.21
1.6.5 1.6.4 1.6.3 1.6.2 1.6.1 1.6.0 1.5.4 1.5.5 1.5.3 1.5.2 1.5.1 1.5.0 1.4.2 1.4.1 1.4.0 1.3.28 1.3.27 1.3.26 1.3.25 1.3.23 1.3.22 1.3.21 1.3.20 1.3.19 trunk All 48 releases
fluent-cart / app / Hooks / Handlers / ShortCodes / Buttons / AddToCartShortcode.php

AddToCartShortcode.php in FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler 1.3.21, at app/Hooks/Handlers/ShortCodes/Buttons/AddToCartShortcode.php

92 lines 2.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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 'text' => $buttonText,
81 'is_shortcode'=> true,
82 ];
83
84 if ($buttonClass) {
85 $atts['class'] = $buttonClass;
86 }
87
88 return (new ProductRenderer($product, $rendererConfig))->renderAddToCartButtonBlock($atts);
89 }
90 }
91
92