使用 DataForm 构建 WordPress 插件设置页

原作者:Róbert Mészáros;原载 WordPress Developer Blog,2026 年 1 月 20 日。中文翻译与技术校订:未完纪。

WordPress 正在推进后台界面重设计。在这个过渡阶段,后台同时存在两套界面:一套是已经沿用十余年的经典界面,另一套是随区块编辑器和站点编辑器出现的现代界面。

如果你正在开发需要设置页的插件,希望它与 WordPress 核心的使用体验保持一致,那么现在就值得采用这些正在成为新标准的设计元素和交互模式。

一种做法是使用 WordPress 的 React 组件搭建设置页。此前的《如何使用 WordPress React 组件构建插件页面》已经介绍过这条路线。过去一年多,社区又推进了不少工作,让我们有了另一种值得尝试的方法。

本文将重建那篇教程中的设置页:原先逐个组合 React 组件,这次改用 DataForm。它用声明式配置创建表单和面板,让你不用为每个控件分别导入对应组件。

先看重构前的设置页:

原文重构前的公告栏设置页:消息文本框、显示开关和可折叠的外观面板
原文重构前的公告栏设置页:消息文本框、显示开关和可折叠的外观面板。图源:Róbert Mészáros / WordPress Developer Blog,原文截图。

完成重构后,设置页会是这样:

原文用 DataForm 重构后的公告栏设置页:消息、显示开关与字号设置
原文用 DataForm 重构后的公告栏设置页:消息、显示开关与字号设置。图源:Róbert Mészáros / WordPress Developer Blog,原文截图。

开始之前

本文默认你已经读过《如何使用 WordPress React 组件构建插件页面》,了解其中实现的公告栏插件。如果还没读过,可以先熟悉那篇教程。

本文不再展开后台页面注册、脚本和样式入队,以及通过 REST API 注册、公开设置的过程。这些内容已在前篇介绍,此次重构不改变它们。

跟随本文操作时,可以下载或克隆 Unadorned Announcement Bar 插件仓库,按仓库说明完成准备。本文从前篇的最终状态继续。

如果某一步遇到问题,可以对照仓库的 dataform-refactor 分支。每个步骤都有独立提交,方便比较变化。

原来的 SettingsPage 组件

原设置页由多个组件组成,并使用一个自定义 Hook 管理状态。

SettingsPage 的代码如下:

const SettingsPage = () => {
    const {
        message,
        setMessage,
        display,
        setDisplay,
        size,
        setSize,
        saveSettings,
    } = useSettings();

    return (
        <>
            <SettingsTitle />
            <Notices />
            <Panel>
                <PanelBody>
                    <PanelRow>
                        <MessageControl
                            value={ message }
                            onChange={ ( value ) => setMessage( value ) }
                        />
                    </PanelRow>
                    <PanelRow>
                        <DisplayControl
                            value={ display }
                            onChange={ ( value ) => setDisplay( value ) }
                        />
                    </PanelRow>
                </PanelBody>
                <PanelBody
                    title={ __( 'Appearance', 'unadorned-announcement-bar' ) }
                    initialOpen={ false }
                >
                    <PanelRow>
                        <SizeControl
                            value={ size }
                            onChange={ ( value ) => setSize( value ) }
                        />
                    </PanelRow>
                </PanelBody>
            </Panel>
            <SaveButton onClick={ saveSettings } />
        </>
    );
};

这些界面元素都来自 @wordpress/components 包。即使是 MessageControl 这样的自定义组件,也只是对 WordPress 现成组件的一层封装:

const MessageControl = ( { value, onChange } ) => {
    return (
        <TextareaControl
            label={ __( 'Message', 'unadorned-announcement-bar' ) }
            value={ value }
            onChange={ onChange }
            __nextHasNoMarginBottom
        />
    );
};

改用 DataForm 后,不再需要为这些字段分别编写控件包装组件,保留一个 DataForm 即可。

安装 @wordpress/dataviews

DataForm 属于 @wordpress/dataviews 包,所以第一步是安装它。

在插件目录中执行下面的安装命令。它会联网解析依赖、修改依赖文件,并可能执行依赖包的安装脚本;本文仅展示命令,没有执行。

npm install @wordpress/dataviews --save

接着,在 /src/components/settings-page.jsx 顶部加入 DataForm 导入:

import { DataForm } from '@wordpress/dataviews/wp';

在原文所用的 WordPress 与 wp-scripts 环境中,应从 @wordpress/dataviews/wp 导入,以正确解析 WordPress 依赖。这与独立应用中的打包方式有别。

加入 DataForm 组件

settings-page.jsx 已经不需要大部分独立控件,因此可以把整个 Panel 及其子组件替换为 DataForm:

const SettingsPage = () => {
    const {
        // ...    
    } = useSettings();

    return (
        <>
            <SettingsTitle />
            <Notices />
            <DataForm />
            <SaveButton onClick={ saveSettings } />
        </>
    );
};

DataForm 需要 data、fields、form 和 onChange 等属性。先给它们空值,随后再逐一补齐。

修改后的 settings-page.jsx 如下:

const SettingsPage = () => {
    const {
        // ...
    } = useSettings();

    const data = {};
    const fields = [];
    const form = {};

    return (
        <>
            <SettingsTitle />
            <Notices />
            <DataForm
                data={ data }
                fields={ fields }
                form={ form }
                onChange={ () => {} }
            />
            <SaveButton onClick={ saveSettings } />
        </>
    );
};

这些属性也可以直接写在 JSX 中。不过,后续配置会占据多行,先用变量承接更容易阅读。

按原文的步骤刷新设置页,此时应只看到标题和“保存”按钮,相当于先清空表单区域。

原文第一步:DataForm 尚未配置字段,页面只显示标题与保存按钮
原文第一步:DataForm 尚未配置字段,页面只显示标题与保存按钮。图源:Róbert Mészáros / WordPress Developer Blog,原文截图。

配置表单字段

DataForm 由配置驱动。定义字段时,至少提供 id、label 和 type。

id 是字段的唯一标识,可以是任意字符串;label 是界面显示的字段名称。

type 的作用之一是定义字段保存的数据类型,例如 text、integer、boolean 和 datetime。随着包的演进,可选类型也会变化;完整清单见字段类型文档。

添加消息字段

消息允许自由输入文本,因此使用 text 类型。

在 settings-page.jsx 中更新 fields 变量。所有字段的定义都放在这里:

const SettingsPage = () => {
    // ...
    
    const data = {};
    const fields = [
        {
            id: 'message',
            label: __( 'Message', 'unadorned-announcement-bar' ),
            type: 'text',
        },
    ];
    const form = {};

    // ..
};

这一步只定义字段,还不会把它显示出来。要渲染消息输入框,还需要在 form 中列出该字段的 id:

const SettingsPage = () => {
    // ...
    
    const data = {};
    const fields = [
        {
            id: 'message',
            // ...
        }
    ];
    const form = {
        fields: [ 'message' ], 
    };

    // ..
};

最后,在 data 中为它设置初始值。这里先让 message 等于空字符串。

settings-page.jsx 中相应的部分变成:

const SettingsPage = () => {
    // ...
    
    const data = {
        message: '',
    };
    const fields = [
        {
            id: 'message',
            // ...
        }
    ];
    const form = {
        fields: [ 'message' ],
    };

    // ..
};

此时刷新插件设置页,按原文演示应当能看到一个文本输入框。

原文配置 message 后出现默认的单行文本输入框
原文配置 message 后出现默认的单行文本输入框。图源:Róbert Mészáros / WordPress Developer Blog,原文截图。

它现在是单行输入框,而不是旧界面的多行文本框;稍后会介绍如何切换。

添加显示开关字段

显示字段采用相同的配置方式。由于它表示开或关,这次使用 boolean 类型。

更新 settings-page.jsx 中的变量:

const SettingsPage = () => {
    // ...
    
    const data = {
        message: '',
        display: false,
    };
    const fields = [
        {
            id: 'message',
            // ...
        },
        {
            id: 'display',
            label: __( 'Display', 'unadorned-announcement-bar' ),
            type: 'boolean',
        },
    ];
    const form = {
        fields: [ 'message', 'display' ],
    };

    // ..
};

刷新页面后,消息字段下方会出现一个复选框。

原文新增 boolean 类型 display 后,消息下方出现复选框
原文新增 boolean 类型 display 后,消息下方出现复选框。图源:Róbert Mészáros / WordPress Developer Blog,原文截图。

添加字号字段

最后一个字段控制字号,用户从 small、medium 等预设选项中选择。

DataForm 没有单独的 select 数据类型。字号值以字符串保存,因此仍使用 text,再通过可选的 elements 属性提供选项。设置了 elements 后,DataForm 会使用选择控件,而不是普通文本输入框。

更新后的 settings-page.jsx 如下:

const SettingsPage = () => {
    // ...
    
    const data = {
        message: '',
        display: false,
        size: 'small',
    };
    const fields = [
        {
            id: 'message',
            // ...
        },
        {
            id: 'display',
            // ...
        },
        {
            id: 'size',
            label: __( 'Font size', 'unadorned-announcement-bar' ),
            type: 'text',
            elements: [
                {
                    value: 'small',
                    label: __( 'Small', 'unadorned-announcement-bar' ),
                },
                {
                    value: 'medium',
                    label: __( 'Medium', 'unadorned-announcement-bar' ),
                },
                {
                    value: 'large',
                    label: __( 'Large', 'unadorned-announcement-bar' ),
                },
                {
                    value: 'x-large',
                    label: __( 'Extra Large', 'unadorned-announcement-bar' ),
                },
            ]
        }
    ];
    const form = {
        fields: [ 'message', 'display', 'size' ],
    };

    // ..
};

至此,设置页已有三个字段。它们都由配置对象定义,不需要逐个导入相应的具体控件。

原文添加带 elements 的 size 字段后,出现字号选择框
原文添加带 elements 的 size 字段后,出现字号选择框。图源:Róbert Mészáros / WordPress Developer Blog,原文截图。

定制字段的界面控件

如果只指定字段的 type,没有额外配置,每种类型会映射到默认界面控件。

例如,未提供 elements 的 text 字段默认是文本输入框,boolean 字段默认是复选框。

通过 Edit 属性可以改变默认控件。最简单的方式是选用预置控件名,如 textarea、toggle、radio 或 toggleGroup。

在 settings-page.jsx 的各字段定义中加入 Edit:

const SettingsPage = () => {
    // ...
    const fields = [
        {
            id: 'message',
            // ...
            Edit: 'textarea',
        },
        {
            id: 'display',
            // ...
            Edit: 'toggle',
        },
        {
            id: 'size',
            // ...
            Edit: 'toggleGroup',
        },
    ];
    // ..
};

这样,三个字段分别使用多行文本框、开关和切换按钮组。

原文设置 Edit 后,三个字段分别呈现多行文本框、开关和切换按钮组
原文设置 Edit 后,三个字段分别呈现多行文本框、开关和切换按钮组。图源:Róbert Mészáros / WordPress Developer Blog,原文截图。

如果内置控件还不够用,也可以提供自己的自定义组件。这样既保留配置驱动的设置页结构,又不受现有控件种类限制。

具体写法和当前内置控件清单见 Edit 文档,可用控件会继续增加。

配置表单布局

字段控件已经与旧页面一致,但布局仍有差别:字段没有放进分组面板,字号设置也没有默认折叠。

DataForm 不仅支持字段配置,也支持配置整个表单的呈现布局。

将字段分组

为了还原旧布局,先把字段分到不同区域。在 settings-page.jsx 中修改 form:

const SettingsPage = () => {
    // ...
    const form = {
        fields: [
            {
                id: 'bar',
                label: __( 'Bar', 'unadorned-announcement-bar' ),
                children: [ 'message', 'display' ],
            },
            {
                id: 'appearance',
                label: __( 'Appearance', 'unadorned-announcement-bar' ),
                children: [ 'size' ],
            },
        ],
    };

    // ..
};

与字段定义一样,分组也需要 id 和 label。区别在于,分组不定义 type,而是通过 children 引用已有字段。

刷新页面,就能看到 Bar 和 Appearance 两个分组。

原文通过 children 把消息及开关分到 Bar,字号分到 Appearance
原文通过 children 把消息及开关分到 Bar,字号分到 Appearance。图源:Róbert Mészáros / WordPress Developer Blog,原文截图。

切换布局类型

DataForm 默认使用 regular 布局,把字段一行一行排列。除此之外,还提供 panel、card 和 row。

card 最接近原来的设计。你也可以对比其他布局,选择适合页面的组合。

要改成卡片布局,更新 settings-page.jsx 的 form 配置:

const SettingsPage = () => {
    // ...
    const form = {
        fields: [
            {
                id: 'bar',
                // ...
                layout: { type: 'card' },
            },
            {
                id: 'appearance',
                // ...
                layout: { type: 'card' },
            },
        ],
    };

    // ..
};

各分组可以采用不同的布局类型,不必整张表单只使用一种布局。

原文为两个字段分组设置 card 卡片布局
原文为两个字段分组设置 card 卡片布局。图源:Róbert Mészáros / WordPress Developer Blog,原文截图。

调整布局选项

不同布局还各有一些额外设置。

例如,card 可以控制是否显示标题,以及卡片初始展开还是折叠。完整选项见布局文档。

要隐藏第一组标题,并让第二组默认折叠,可以这样修改 layout:

const SettingsPage = () => {
    // ...
    const form = {
        fields: [
            {
                id: 'bar',
                // ...
                layout: { type: 'card', withHeader: false },
            },
            {
                id: 'appearance',
                // ...
                layout: { type: 'card', isOpened: false },
            },
        ],
    };

    // ..
};

完成这一步,界面已经与重构前十分接近。

原文隐藏第一张卡片标题并让外观卡片初始折叠
原文隐藏第一张卡片标题并让外观卡片初始折叠。图源:Róbert Mészáros / WordPress Developer Blog,原文截图。

个别元素的间距和宽度仍需微调,可以使用 VStack 和自定义 CSS。

少量样式调整后,原文展示的最终效果如下:

原文最终界面:经过 VStack 和 CSS 间距调整的 DataForm 设置页
原文最终界面:经过 VStack 和 CSS 间距调整的 DataForm 设置页。图源:Róbert Mészáros / WordPress Developer Blog,原文截图。

CSS 不属于本文的主要内容,具体实现见仓库中的对应提交。

把 DataForm 接到 settings 状态

现在页面已经能够呈现,但传给 DataForm 的 data 还是写死的临时值,onChange 也尚未实现:

const SettingsPage = () => {
    const {
        // ...
    } = useSettings();

    const data = {
        message: '',
        display: false,
        size: 'small',
    };
    // ...

    return (
        <>
            <SettingsTitle />
            <Notices />
            <DataForm
                data={ data }
                fields={ fields }
                form={ form }
                onChange={ () => {} }
            />
            <SaveButton onClick={ saveSettings } />
        </>
    );
};

最后一步是把 DataForm 与负责状态管理的自定义 useSettings Hook 连接起来。

重构 useSettings

原实现分别调用三次 useState 保存三个字段,但读写设置时,却把它们作为一个对象放在 unadorned_announcement_bar 键下。

先回顾 /src/hooks/use-settings.js 中旧的 Hook:

const useSettings = () => {
    const [ message, setMessage ] = useState();
    const [ display, setDisplay ] = useState();
    const [ size, setSize ] = useState();

    const { createSuccessNotice } = useDispatch( noticesStore );

    useEffect( () => {
        apiFetch( { path: '/wp/v2/settings' } ).then( ( wpSettings ) => {
            setMessage( wpSettings.unadorned_announcement_bar.message );
            setDisplay( wpSettings.unadorned_announcement_bar.display );
            setSize( wpSettings.unadorned_announcement_bar.size );
        } );
    }, [] );

    const saveSettings = () => {
        apiFetch( {
            path: '/wp/v2/settings',
            method: 'POST',
            data: {
                unadorned_announcement_bar: {
                    message,
                    display,
                    size,
                },
            },
        } ).then( () => {
            createSuccessNotice(
                __( 'Settings saved.', 'unadorned-announcement-bar' )
            );
        } );
    };

    return {
        message,
        setMessage,
        display,
        setDisplay,
        size,
        setSize,
        saveSettings,
    };
};

设置在服务器端已经注册,并定义了默认值和 schema。原来的注册代码如下:

function unadorned_announcement_bar_settings() {
    $default = array(
        'message' => __( 'Hello, World!', 'unadorned-announcement-bar' ),
        'display' => true,
        'size'    => 'medium',
    );
    $schema  = array(
        'type'       => 'object',
        'properties' => array(
            'message' => array(
                'type' => 'string',
            ),
            'display' => array(
                'type' => 'boolean',
            ),
            'size'    => array(
                'type' => 'string',
                'enum' => array(
                    'small',
                    'medium',
                    'large',
                    'x-large',
                ),
            ),
        ),
    );

    register_setting(
        'options',
        'unadorned_announcement_bar',
        array(
            'type'         => 'object',
            'default'      => $default,
            'show_in_rest' => array(
                'schema' => $schema,
            ),
        )
    );
}

add_action( 'init', 'unadorned_announcement_bar_settings' );

现在,字段不再各有一个包装组件,DataForm 的 data 也要求传入对象。因此,用一个对象保存字段状态更直接,也与数据库中的设置结构一致。

先把 use-settings.js 中三个独立状态换成一个对象状态。译校修正:原文这一过渡片段返回数组,但后面的完整 Hook 返回对象;本文统一采用对象返回,避免调用方混用。

const useSettings = () => {
    const [ settings, setSettings ] = useState( {
        message: '',
        display: false,
        size: 'small',
    } );

    // ...

    return { settings, setSettings, saveSettings };
};

数据库 options 表中的数据结构与状态对象一致后,读取和保存也可以相应简化。

首次加载时,更新 useEffect 中的成功回调:

const useSettings = () => {
    // ...

    useEffect( () => {
        apiFetch( { path: '/wp/v2/settings' } ).then( ( wpSettings ) => {
            setSettings( wpSettings.unadorned_announcement_bar )
        } );
    }, [] );

    // ...
};

保存时,把 saveSettings 改为直接提交整个设置对象:

const useSettings = () => {
    // ...

    const saveSettings = () => {
        apiFetch( {
            path: '/wp/v2/settings',
            method: 'POST',
            data: {
                unadorned_announcement_bar: settings
            },
        } ).then( () => {
            // ...
        } );
    };

    // ...
};

把前面的变化组合起来,useSettings 如下。它保留原文教学实现,尚未加入加载失败和保存失败处理;这些限制在文末单独列出。

const useSettings = () => {
    const [settings, setSettings] = useState({
        message: "",
        display: false,
        size: "small",
    });

    const { createSuccessNotice } = useDispatch(noticesStore);

    useEffect(() => {
        apiFetch({ path: "/wp/v2/settings" }).then((wpSettings) => {
            setSettings(wpSettings.unadorned_announcement_bar);
        });
    }, []);

    const saveSettings = () => {
        apiFetch({
            path: "/wp/v2/settings",
            method: "POST",
            data: {
                unadorned_announcement_bar: settings,
            },
        }).then(() => {
            createSuccessNotice(
                __("Settings saved.", "unadorned-announcement-bar"),
            );
        });
    };

    return {
        settings,
        setSettings,
        saveSettings,
    };
};

连接 useSettings 与 DataForm

useSettings 现在使用一个对象保存字段状态,需要同步更新 SettingsPage。

修改 Hook 返回值的解构方式,删除临时 data 变量,把 settings 直接传给 DataForm。

/src/components/settings-page.jsx 如下。译校修正:原文此处写成数组解构,与上一段完整 Hook 的对象返回不一致。这里改用对象解构,其余连接方式保持不变。

const SettingsPage = () => {
    const { settings, setSettings, saveSettings } = useSettings();
    
    const fields = [
        // ...
    ]
    const form = {
        // ..
    }

    return (
        <>
            <SettingsTitle />
            <Notices />
            <DataForm
                data={ settings }
                fields={ fields }
                form={ form }
                onChange={ () => {} }
            />
            <SaveButton onClick={ saveSettings } />
        </>
    );
};

实现 onChange 回调

最后,在字段改变时更新内部 settings 状态。这由 onChange 回调完成。

onChange 只接收修改过的数据,即 edits,而不是完整状态。例如修改消息字段后,回调拿到的可能是 { message: 'updated value' }。

所以不能把 edits 直接传给 setSettings,否则整个对象会被替换,只剩下这一个字段。正确做法是把修改合并到当前状态。

onChange 可以这样实现:

const SettingsPage = () => {
    // ...

    return (
        <>
            <SettingsTitle />
            <Notices />
            <DataForm
                data={ settings }
                fields={ fields }
                form={ form }
                onChange={ ( edits ) =>
                    setSettings( ( current ) => ( {
                        ...current,
                        ...edits,
                    } ) )
                }
            />
            <SaveButton onClick={ saveSettings } />
        </>
    );
};

展开语法 ... 先复制 current 的全部属性,再用 edits 中同名属性覆盖。未改动的字段因此保留原值,改动的字段则得到新值。

至此,使用 DataForm 和配置驱动方式重构设置页的流程就完成了。这里描述的是原文的实现步骤,并不表示本译稿已运行或验证插件。

继续实践

查看完整实现

完整代码见 GitHub 的 dataform-refactor 分支,也可以比较两种实现。

原文还提供了 WordPress Playground 演示入口,便于在浏览器沙箱中体验。本文保留源文入口链接,不自动加载或安装插件;原示例的 Playground 配置指定 PHP 8.3 与 WordPress 6.9。

还可以探索什么

如果想进一步使用 DataForm,还可以研究下面这些能力。

校验机制支持客户端校验、必填字段等规则。客户端校验有助于交互,但不能取代服务器端的权限和输入校验。

选项不一定要写死在 elements 中,也可以异步加载,例如从数据库动态读取下拉选项。

Storybook 中的 DataForm 页面提供不同布局及组合方式的交互演示。

了解本文所依据的版本变化,可以先读《WordPress 6.9 中的 DataViews、DataForm 等变化》,具体 API 则以所安装版本对应的包文档为准。

原作者感谢 @psykro、@areziaal 的审阅,以及 @juanmaguitar 持续开展的相关教学工作。

译校附记:复制代码前需要知道的边界

返回值修正。原文重构中间片段写作 return [ settings, setSettings, saveSettings ],而完整 Hook 改成 return { settings, setSettings, saveSettings };后面的调用示例却继续使用数组解构。普通对象不能这样按迭代器解构,会产生运行错误。本文把中间片段和调用方统一为对象形式。修正来自静态检查,没有执行证明。

加载与保存。原文 Hook 的 GET 和 POST 只有成功处理,没有 catch,也没有“尚未加载”“正在保存”等状态。初始状态 { message: '', display: false, size: 'small' } 与服务器默认值不同;如果首次读取尚未完成就点击保存,可能覆盖已有设置。如果用户正在编辑时首次 GET 才返回,也可能把编辑内容替换掉。生产实现应在成功读取并校验响应后再启用编辑、保存;保存期间禁止重复提交,并显示加载或保存失败。不能用默认空值掩盖读取失败。应验证返回值为对象,message 为字符串、display 为布尔值、size 属于四个允许值,再交给表单。

权限与输入。前篇把后台菜单能力设置为 manage_options,通过 WordPress 的设置 REST 端点读写,并注册服务端 schema。这些边界应保留,不能因为界面隐藏了某个字段就认为它受到保护。登录态请求应使用 WordPress 正常的 cookie/nonce 机制;本译稿没有读取任何凭据,也未验证具体站点的权限配置。客户端的 type、elements 或校验只服务于交互,不能代替服务端授权和验证。

输出转义。前篇输出公告消息使用 esc_html(),样式属性使用 esc_attr()。重构表单不能删掉这些处理,更不能把用户提供的消息传入 dangerouslySetInnerHTML。原 schema 限定 REST 写入的字号枚举,但其他代码仍可能直接修改 option,因此读取端仍应检查数据形状并按实际输出语境转义。

版本和安装。WordPress 6.9 的发布说明记录了 boolean 字段类型及 card/row 布局等扩展。不能据此假定老版本 WordPress 内置依赖拥有这些 API,也不能把 2026 年 1 月的命令理解为可永久复现的版本锁定方案。正式项目应保存依赖锁文件,核对 @wordpress/scripts、@wordpress/dataviews 和目标 WordPress 版本的配合,再在隔离开发环境进行构建与交互验证。本文不提供未经核验的“当前最新版”版本号。

审查范围。本文代码仅经过静态阅读;没有启动插件、写入数据库、运行依赖安装或执行生产操作。静态审查未发现硬编码密码或令牌,但这不等于完成了漏洞审计。

来源与许可

图片为原作者文章中的实际截图,保留作者与来源归属,未伪称本次运行结果。WordPress 名称及标志的权利归其相应权利人所有。

配套示例代码许可

原插件作者 Róbert Mészáros,源码头注明 GPLv2 or later;下列原许可头与 GNU GPL 第2版全文保留。文中编校修正均另行标注,修改日期 2026-10-05;原代码及其衍生代码保持 GPLv2 or later。文章说明和截图不因软件许可而被改称 GPL 作品。

<?php
/**
 * Plugin Name: Unadorned Announcement Bar
 * Plugin URI: https://github.com/wptrainingteam/unadorned-announcement-bar
 * Description: A companion plugin for a WordPress Developer Blog article.
 * Version: 2.0.0
 * Requires at least: 6.1
 * Requires PHP: 7.4
 * Author: Róbert Mészáros
 * Author URI: https://www.meszarosrob.com/
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Text Domain: unadorned-announcement-bar
 *
 * @package unadorned-announcement-bar
 */

                    GNU GENERAL PUBLIC LICENSE
                       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

                    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

                            NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容