59 lines
2.3 KiB
PHP
59 lines
2.3 KiB
PHP
<?php
|
|
/**
|
|
* 注册短代码: [yoone_bundle_selector use_current_product="yes" product_id="123"]
|
|
* 作用:在任何页面/文章中插入混装产品选择与加购表单。
|
|
*/
|
|
defined('ABSPATH') || exit;
|
|
|
|
if (! class_exists('Yoone_PB_Shortcodes')) {
|
|
class Yoone_PB_Shortcodes {
|
|
public static function init() {
|
|
add_action('init', array(__CLASS__, 'register_shortcodes'));
|
|
}
|
|
|
|
public static function register_shortcodes() {
|
|
add_shortcode('yoone_bundle_selector', array(__CLASS__, 'shortcode_bundle_selector'));
|
|
}
|
|
|
|
/**
|
|
* 渲染短代码内容
|
|
* @param array $atts
|
|
* @param string|null $content
|
|
* @return string
|
|
*/
|
|
public static function shortcode_bundle_selector($atts, $content = null) {
|
|
$atts = shortcode_atts(array(
|
|
'use_current_product' => 'yes', // yes|no
|
|
'product_id' => 0,
|
|
), $atts, 'yoone_bundle_selector');
|
|
|
|
$use_current = strtolower($atts['use_current_product']) === 'yes' || $atts['use_current_product'] === '1' || $atts['use_current_product'] === 1;
|
|
$product_id = absint($atts['product_id']);
|
|
|
|
// 解析产品对象
|
|
$product = null;
|
|
if ($use_current && function_exists('is_singular') && 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 || ! method_exists($product, 'get_type') || $product->get_type() !== Yoone_Product_Bundles::TYPE) {
|
|
return '<div class="yoone-pb-shortcode-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();
|
|
}
|
|
}
|
|
|
|
// 启动短代码注册
|
|
Yoone_PB_Shortcodes::init();
|
|
} |