Skip to content

estevan-ulian/wp-preact-plugin

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

WP Preact Plugin

A WordPress plugin with Preact frontend integration using Vite.

πŸ“‹ Description

This plugin provides the basic setup to integrate a Preact application into a WordPress site. It enables you to create modern and reactive interfaces using Preact technology within WordPress and use them through shortcodes.

Example

✨ Features

  • ⚑ Preact + Vite: Fast builds and lightweight application
  • πŸ”„ TypeScript: Static typing for enhanced code safety
  • πŸ“¦ Build System: Automated generation of optimized files
  • 🎯 Shortcode Support: Easy integration with WordPress pages/posts
  • πŸ”— PHP ↔ Frontend Communication: Seamless data passing from backend to frontend

πŸš€ Requirements

  • PHP >= 7.4
  • WordPress 6.0+
  • Node.js >= 18
  • Composer

πŸ“¦ Installation

1. Clone or extract the plugin

cd wp-content/plugins/
# Place the plugin files here

2. Install PHP dependencies

composer install

3. Install Node.js dependencies

cd frontend
npm install

πŸ› οΈ Development

Development Mode (Frontend)

To work on the frontend with hot reload:

cd frontend
npm run dev

This will start the Vite development server on the default port (5173).

IMPORTANT
When working in development mode, data passed from PHP (backend) to the frontend via wp_localize_script will not be available, as Vite serves the files directly. To test PHP β†’ Frontend communication, you'll need to do a temporary production build or implement an alternative solution to inject the data during development.

The current solution creates fallbacks for all values passed from PHP (backend) to the frontend. In this example, the strings constant located in frontend/src/core/config.ts has fallbacks for demonstration purposes.

Frontend Build

To compile the frontend for production:

cd frontend
npm run build

This will generate optimized files in the assets/ folder:

  • assets/js/wp-preact-plugin.js
  • assets/css/wp-preact-plugin.css

Building the ZIP Plugin for Distribution

To create a ZIP file ready for distribution:

composer build

or

php Build.php

This will create the build/wp-preact-plugin.zip file containing only the necessary files to run the plugin on a WordPress site.

πŸ“– Usage

Activating the Plugin

  1. Access the WordPress admin panel
  2. Go to Plugins β†’ Installed Plugins
  3. Activate Wordpress Preact Plugin

Using the Shortcode

In any page or post, add the shortcode:

[wp_preact_plugin]

This will render the Preact application at the desired location.

πŸ—οΈ Project Structure

wp-preact-plugin/
β”œβ”€β”€ main.php                    # Main plugin file
β”œβ”€β”€ index.php                   # Security file
β”œβ”€β”€ Build.php                   # Build script
β”œβ”€β”€ build-config.json           # Build configuration
β”œβ”€β”€ composer.json               # PHP dependencies
β”‚
β”œβ”€β”€ includes/                   # PHP classes
β”‚   └── shortcodes/
β”‚       └── wp-preact-shortcode.php  # Shortcode implementation
β”‚
β”œβ”€β”€ frontend/                  # Preact application
β”‚   β”œβ”€β”€ package.json           # Node dependencies
β”‚   β”œβ”€β”€ vite.config.ts         # Vite configuration
β”‚   β”œβ”€β”€ tsconfig.json          # TypeScript configuration
β”‚   β”‚
β”‚   β”œβ”€β”€ public/                # Static files
β”‚   β”‚   └── vite.svg
β”‚   β”‚
β”‚   └── src/                   # Source code
β”‚       β”œβ”€β”€ main.tsx           # Entry point
β”‚       β”œβ”€β”€ app.tsx            # Main component
β”‚       β”œβ”€β”€ app.css            # Global styles
β”‚       β”‚
β”‚       β”œβ”€β”€ core/
β”‚       β”‚   └── config.ts      # App configuration
β”‚       β”‚
β”‚       └── components/
β”‚           └── SimpleCounter/  # Example component
β”‚               β”œβ”€β”€ index.tsx
β”‚               └── styles.css
β”‚
β”œβ”€β”€ assets/                    # Compiled files (generated)
β”‚   β”œβ”€β”€ css/
β”‚   β”‚   └── wp-preact-plugin.css
β”‚   └── js/
β”‚       └── wp-preact-plugin.js
β”‚
β”œβ”€β”€ build/                     # ZIP builds (generated)
β”‚   └── wp-preact-plugin.zip
β”‚
└── vendor/                    # PHP dependencies (generated)

πŸ”„ PHP β†’ Frontend Communication Flow

1. In PHP (includes/shortcodes/wp-preact-shortcode.php)

Data is passed via wp_localize_script:

// ...
wp_localize_script(
  'wp-preact-plugin-js',
  'wp_preact_plugin_args', // global JS variable
  array(
    'root' => 'wp_preact_plugin_root',
    'assets_url' => WPPreactPlugin::get_asset_url(''),
    'strings' => array(
      'example' => 'This is an example value from PHP',
      'start_counter' => 123,
    ),
  )
);
// ...

2. In Frontend (frontend/src/core/config.ts)

Data is accessed via window.wp_preact_plugin_args:

// Remember to always update the Window interface when 
// data or strings are added, removed, or changed
// in the backend. This ensures proper TypeScript typing.
declare global {
  interface Window {
    wp_preact_plugin_args: {
      root: string;
      assets_url: string;
      strings: {
        example: string;
        start_counter: number;
      }
    }
  }
}

const wpPreactPluginArgs = window.wp_preact_plugin_args || {};

const root = document.getElementById(wpPreactPluginArgs.root || "app") as HTMLElement;

// If you don't provide strings from PHP, use these defaults to avoid 
// undefined errors in the app. This is useful for development using 
// `npm run dev` command. To see the real strings from PHP, use 
// `npm run build` and load the plugin in WordPress.
const strings = wpPreactPluginArgs.strings || {
  example: "Default example string",
  start_counter: 0,
}

export const appConfig = Object.freeze({
    root,
    baseAssetsUrl: wpPreactPluginArgs.assets_url,
    strings: strings,
});

3. Using in Components

import { appConfig } from './core/config';

// Access strings
<h1>{appConfig.strings.example}</h1>
<span>{appConfig.strings.start_counter}</span>

// Access assets URL (essential for static files 
// like images, fonts, etc. located in /frontend/public)
<img src={`${appConfig.baseAssetsUrl}/image.jpg`} />

🎯 How It Works

1. Plugin Registration

The main.php file registers the plugin in WordPress and defines basic information.

2. Shortcode

The WPPreactPluginShortcode class in includes/shortcodes/wp-preact-shortcode.php:

  • Registers scripts and styles
  • Creates the [wp_preact_plugin] shortcode
  • Renders the <div id="wp_preact_plugin_root">
  • Enqueues scripts only when the shortcode is used

3. Frontend

Vite compiles the TypeScript/Preact code into single JavaScript and CSS files that are loaded in WordPress.

4. Mounting

The main.tsx mounts the Preact application in the div created by the shortcode.

🎨 Adding New Components

  1. Create a new folder in frontend/src/components/:
mkdir frontend/src/components/MyComponent
  1. Create the index.tsx file:
import { useState } from 'preact/hooks';
import './styles.css';

export function MyComponent() {
    return (
        <div>
            <h2>My Component</h2>
        </div>
    );
}
  1. Create styles.css (optional):
/* Component styles */
  1. Import in app.tsx:
import { MyComponent } from './components/MyComponent';

export function App() {
    return (
        <div>
            <MyComponent />
        </div>
    );
}

πŸ“ Passing Custom Data to the Frontend

To pass different data for each shortcode instance:

1. Send data via shortcode attributes:

/**
 * Shortcode callback function     
 * @param array $atts Shortcode attributes
 * @return string HTML output of the shortcode
 */
public function shortcode_callback($atts)
{
  // Enqueue registered scripts and styles only when shortcode is used
  wp_enqueue_style('wp-preact-plugin-css');
  wp_enqueue_script('wp-preact-plugin-js');

  // Pass data and strings to frontend via wp_localize_script
  wp_localize_script(
    'wp-preact-plugin-js',
    'wp_preact_plugin_args',
    array(
      'root' => 'wp_preact_plugin_root',
      'assets_url' => WPPreactPlugin::get_asset_url(''),
      'strings' => array(
        'example' => 'This is an example value from PHP',
        'start_counter' => 123,
        'data_from_atts' => isset($atts['data']) ? $atts['data'] : 'default value',
        'another_data_from_atts' => isset($atts['another_data']) ? $atts['another_data'] : 'another default value',
      ),
    )
  );    
  // ...
}

2. Use in WordPress:

[wp_preact_plugin data_from_atts="some data value from atts..." another_data_from_atts="another data value from atts..."]

πŸ”§ Build Configuration

The build-config.json file controls what is included in the final ZIP:

{
  // Include only necessary files and folders
  "include": ["main.php", "index.php", "includes", "assets"],
  // Exclude Vite HTML file. This file is not needed in the WordPress plugin (production).
  "exclude": ["assets/index.html"] 
}
  • include: Files/folders to include
  • exclude: Files/folders to remove from the build

πŸ“š Technologies Used

Backend (PHP)

  • WordPress Plugin API
  • Composer (dependency manager)
  • Symfony Components (Filesystem, Finder, Console)

Frontend

  • Preact: Lightweight UI library (React alternative)
  • TypeScript: JavaScript superset with static typing
  • Vite: Modern and fast build tool
  • @preact/preset-vite: Vite preset for Preact

πŸ› Troubleshooting

Scripts not loading

  • Make sure you ran npm run build in the frontend folder
  • Check if files exist in assets/js/ and assets/css/

TypeScript errors

  • Run npm install again in the frontend folder
  • Check versions in package.json

Plugin doesn't appear in WordPress

  • Verify the plugin is in the wp-content/plugins/ folder
  • Confirm the main.php file exists

ZIP build fails

  • Run composer install to install PHP dependencies
  • Check permissions for the build/ folder

πŸ“„ License

This project is licensed under the MIT License. See the LICENSE file for more details.

🀝 Contributing

Contributions are welcome! Feel free to open issues or pull requests.

About

A WordPress plugin with Preact frontend integration using Vite.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors