90 lines
3.0 KiB
PHP
90 lines
3.0 KiB
PHP
<?php
|
||
/**
|
||
* Plugin Name: 🔵 React Product Loader
|
||
* Description: ショートコードにより、あらゆるページに独立したReactアプリを柔軟に組み込めます。 | 通过短代码在任意页面中灵活嵌入独立的 React 应用 | `[react_app app_name="alisurvey"]`
|
||
* Version: 1.0.0
|
||
* Author: 薛家豪
|
||
* Text Domain: react-product-loader
|
||
*/
|
||
|
||
defined( 'ABSPATH' ) || exit;
|
||
|
||
/**
|
||
* 注册短代码 [react_app]
|
||
*/
|
||
add_shortcode( 'react_app', 'rpl_react_app_shortcode' );
|
||
function rpl_react_app_shortcode( $atts ) {
|
||
$attributes = shortcode_atts( array(
|
||
'app_name' => 'default-app',
|
||
'mount_id' => 'root'
|
||
), $atts );
|
||
|
||
$app_name = preg_replace( '/[^a-zA-Z0-9\-_]/', '', $attributes['app_name'] );
|
||
$mount_id = esc_attr( $attributes['mount_id'] );
|
||
|
||
return '<div id="' . $mount_id . '"></div>';
|
||
}
|
||
|
||
/**
|
||
* 加载React资源
|
||
*/
|
||
add_action( 'wp_enqueue_scripts', 'rpl_enqueue_react_app_assets' );
|
||
function rpl_enqueue_react_app_assets() {
|
||
global $post;
|
||
|
||
if ( ! is_a( $post, 'WP_Post' ) || ! has_shortcode( $post->post_content, 'react_app' ) ) {
|
||
return;
|
||
}
|
||
|
||
preg_match_all( '/' . get_shortcode_regex() . '/', $post->post_content, $matches, PREG_SET_ORDER );
|
||
$found_shortcodes = array();
|
||
|
||
foreach ( $matches as $shortcode ) {
|
||
if ( $shortcode[2] === 'react_app' ) {
|
||
$parsed_attr = shortcode_parse_atts( $shortcode[3] );
|
||
$found_shortcodes[] = $parsed_attr;
|
||
}
|
||
}
|
||
|
||
if ( ! empty( $found_shortcodes ) ) {
|
||
$attr = $found_shortcodes[0];
|
||
$app_name = isset( $attr['app_name'] ) ? preg_replace( '/[^a-zA-Z0-9\-_]/', '', $attr['app_name'] ) : 'alisurvey';
|
||
$mount_id = isset( $attr['mount_id'] ) ? esc_attr( $attr['mount_id'] ) : 'root';
|
||
|
||
$app_url = content_url( '/products/react-apps/' . $app_name . '/' );
|
||
$app_path = WP_CONTENT_DIR . '/products/react-apps/' . $app_name . '/';
|
||
|
||
// 直接查找资产文件
|
||
$js_files = glob( $app_path . 'assets/index-*.js' );
|
||
$css_files = glob( $app_path . 'assets/index-*.css' );
|
||
|
||
if ( ! empty( $js_files ) ) {
|
||
$js_file = basename( $js_files[0] );
|
||
wp_enqueue_script(
|
||
'rpl-app-js-' . $app_name,
|
||
$app_url . 'assets/' . $js_file,
|
||
array(),
|
||
null,
|
||
true
|
||
);
|
||
}
|
||
|
||
if ( ! empty( $css_files ) ) {
|
||
$css_file = basename( $css_files[0] );
|
||
wp_enqueue_style(
|
||
'rpl-app-css-' . $app_name,
|
||
$app_url . 'assets/' . $css_file,
|
||
array(),
|
||
null
|
||
);
|
||
}
|
||
|
||
// 加载Font Awesome(如果需要)
|
||
wp_enqueue_style(
|
||
'rpl-font-awesome',
|
||
'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css',
|
||
array(),
|
||
'6.7.2'
|
||
);
|
||
}
|
||
} |