__('Pre-selected Products', 'wp-ultimo'), 'id' => 'products', ]; } /** * Returns the list of additional fields specific to this type. * * @since 2.0.0 * @return array */ public function get_fields() { return [ 'products' => [ 'type' => 'model', 'title' => __('Products', 'wp-ultimo'), 'placeholder' => __('Products', 'wp-ultimo'), 'desc' => __('Use this field to pre-select products. This is useful when you have a signup page for specific offering/bundles and do not want your customers to be able to choose plans and other products manually.', 'wp-ultimo'), 'tooltip' => '', 'html_attr' => [ 'data-model' => 'product', 'data-value-field' => 'id', 'data-label-field' => 'name', 'data-search-field' => 'name', 'data-max-items' => 10, ], ], ]; } /** * Returns the field/element actual field array to be used on the checkout form. * * @since 2.0.0 * * @param array $attributes Attributes saved on the editor form. * @return array An array of fields, not the field itself. */ public function to_fields_array($attributes) { $checkout_fields = []; $products = explode(',', (string) $attributes['products']); foreach ($products as $product_id) { $checkout_fields[ "products[{$product_id}]" ] = [ 'type' => 'hidden', 'value' => $product_id, 'html_attr' => [ 'v-bind:name' => "'products[]'", ], ]; } $this->insert_products_in_form($products); return $checkout_fields; } /** * Inserts the products in the form. * * @param array $products An array of product IDs. * @return void */ protected function insert_products_in_form(array $products): void { static $added = false; if ($added) { return; } $added = true; $script = "wp.hooks.addFilter('wu_before_form_init', 'nextpress/wp-ultimo', function(data) { if (typeof data !== 'undefined' && Array.isArray(data.products)) { data.products.push(...%s); data.products = data.products.map((value) => parseInt(value) || value); data.products = [...new Set(data.products)]; } return data; });"; if (did_action('wu-checkout')) { wp_add_inline_script('wu-checkout', sprintf($script, json_encode($products)), 'before'); return; } add_action( 'wp_enqueue_scripts', function () use ($script, $products) { wp_add_inline_script('wu-checkout', sprintf($script, json_encode($products)), 'before'); }, 11 ); } }