yoone-wc-product-bundles/includes/blocks/register.php

78 lines
3.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* 注册 Gutenberg 区块Yoone Bundle Selector混装产品选择与加购
*/
defined('ABSPATH') || exit;
class Yoone_PB_Blocks {
protected static $instance = null;
public static function instance() {
if (null === self::$instance) self::$instance = new self();
return self::$instance;
}
private function __construct() {
add_action('init', array($this, 'register_blocks'));
}
public function register_blocks() {
// 注册编辑器脚本
// 计算插件主文件路径,确保 plugins_url 基准正确
$plugin_file = dirname(__DIR__) . '/yoone-product-bundles.php';
wp_register_script(
'yoone-pb-blocks',
plugins_url('assets/js/blocks/bundle-selector.js', $plugin_file),
array('wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n'),
defined('YOONE_PB_VERSION') ? YOONE_PB_VERSION : '0.1.0',
true
);
register_block_type('yoone/bundle-selector', array(
'editor_script' => 'yoone-pb-blocks',
'render_callback' => array($this, 'render_bundle_selector_block'),
'attributes' => array(
'useCurrentProduct' => array('type' => 'boolean', 'default' => true),
'productId' => array('type' => 'integer', 'default' => 0),
),
'supports' => array('anchor' => true),
));
}
/**
* 动态渲染区块内容在产品页或指定产品ID下渲染混装选择表单。
*/
public function render_bundle_selector_block($attributes, $content) {
// 仅在前端渲染;编辑器中显示占位提示
if (is_admin() && function_exists('wp_doing_ajax') && ! wp_doing_ajax()) {
return '<div class="yoone-pb-block-preview">' . esc_html__('Yoone Bundle Selector (预览):此区块在产品页前端渲染完整选择表单。', 'yoone-product-bundles') . '</div>';
}
$use_current = ! empty($attributes['useCurrentProduct']);
$product_id = absint(isset($attributes['productId']) ? $attributes['productId'] : 0);
// 确定要渲染的产品对象
$product = null;
if ($use_current && is_singular('product')) {
global $post;
if ($post) $product = wc_get_product($post->ID);
} elseif ($product_id > 0) {
$product = wc_get_product($product_id);
}
// 安全检查:仅对我们定义的混装产品类型渲染表单
if (! $product || $product->get_type() !== Yoone_Product_Bundles::TYPE) {
return '<div class="yoone-pb-block-notice">' . esc_html__('请选择或切换到一个“Mix and Match (Yoone Bundle)”产品以显示表单。', 'yoone-product-bundles') . '</div>';
}
// 前端资源
wp_enqueue_style('yoone-pb-frontend');
wp_enqueue_script('yoone-pb-frontend');
// 复用插件模板输出完整表单
ob_start();
wc_get_template('global/yoone-bundle-form.php', array(), '', YOONE_PB_PATH . 'templates/');
return ob_get_clean();
}
}