enhance-dev/enhance-wordpress-plugin

一个使用Enhance SSR PHP库在服务器上渲染Web组件的WordPress插件

安装: 5

依赖者: 0

建议者: 0

安全性: 0

星标: 18

关注者: 2

分支: 0

公开问题: 4

语言:JavaScript

类型:wordpress-plugin

v0.0.3 2024-04-29 20:54 UTC

This package is auto-updated.

Last update: 2024-09-07 19:05:13 UTC


README

此插件在WordPress网站上服务器端渲染增强组件。它处于实验阶段,可能还不适合在生产环境中使用。

包含两个插件

  1. enhance-ssr-wp-plugin.php 在WordPress网站上服务器端渲染任何增强自定义元素。这些元素可以添加到PHP模板、编辑器的原始HTML块或预定义块中。

  2. enhance-wp-blocks-plugin.php 展示了如何包装增强组件以在块编辑器中使用。这与SSR插件兼容。这些块以HTML(例如,Hi)的形式存储在WP数据库中,然后SSR插件将它们扩展到它们被使用的地方。

直接安装插件

要将插件添加到WordPress项目,您可以将其克隆到项目插件目录中的一个文件夹中。所有必需的依赖项都包含在仓库的vendor目录中,因此运行composer install通常不需要。

使用Composer安装插件

Composer也可以用来将插件安装到WordPress项目中。

composer require enhance-dev/enhance-wordpress-plugin

WordPress开发副本说明

示例

编写元素

Enhance元素是接受state并返回HTML的纯函数。以下是一个/elements/my-header.js的示例

<?php
function MyHeader($state) {
  return "<style>h1 { color: red; }</style><h1><slot></slot></h1>";
}

这也可以写成一个HTML文件,因为它不依赖于$state,如下所示:

  <style>
    h1 { color: red; }
  </style>
  <h1>
    <slot></slot>
  </h1>

使用元素

此元素被编写为HTML网络组件或自定义元素(例如,<my-header>Cool</my-header>)。使用SSR插件,这些可以在WordPress网站的任何地方使用,并且插件将在将它们发送到浏览器之前将它们展开。它们可以直接使用

  1. 直接在PHP模板中 single.php模板中的my-header标签

  2. 在任何原始HTML块中 原始HTML块中的my-header标签

  3. 作为Gutenburg块 WP编辑器中的my-header

Enhance元素作为Gutenburg块

新的WordPress块编辑器使用React作为编辑器和渲染单独块的工具,然后将它们作为纯HTML存储在数据库中。Enhance元素是运行在服务器上以渲染纯HTML的纯函数。这并不意味着它们不能有客户端JavaScript,但基本体验是HTML。以下是如何包装Enhance元素以便它们可以在块编辑器中工作的一种方法

// custom-blocks/my-header.js
( function( blocks, element, blockEditor ) {
    let el = element.createElement;
    let RichText = blockEditor.RichText;

    blocks.registerBlockType( 'enhance-plugin/my-header-block', {
        title: 'My Header',
        icon: 'heading',
        category: 'layout',
        attributes: {
            content: {
                type: 'string',
                source: 'html',
                selector: 'my-header',
            },
        },
        edit: function( props ) {
            var content = props.attributes.content;
            function onChangeContent( newContent ) {
                props.setAttributes( { content: newContent } );
            }

            return el(
                RichText,
                {
                    tagName: 'h1',
                    className: 'my-custom-header',
                    style: { color: 'red' },
                    value: content,
                    onChange: onChangeContent,
                }
            );
        },
        // Save should be the authored/non-expanded html form of my-header (i.e. `<my-header>Hello World</my-header>`)
        save: function( props ) {
            const htmlContent = props.attributes.content
            return el( 'my-header', { dangerouslySetInnerHTML: { __html: htmlContent } } , null );
        },
      }
    );
} )( window.wp.blocks, window.wp.element, window.wp.blockEditor );