wptrt/admin-notices

一个用于在WordPress仪表板上创建admin-notices的类。

v1.0.4 2023-10-06 03:42 UTC

This package is auto-updated.

Last update: 2024-09-09 13:17:44 UTC


README

这是一个自定义类,允许WordPress主题作者向WordPress仪表板添加admin通知。其主要目的是提供一种标准化的方法,以默认WordPress样式以一致的方式创建admin通知。

使用此方法创建的通知可以自动消失。

使用方法

$my_theme_notices = new \WPTRT\AdminNotices\Notices();

// Add a notice.
$my_theme_notices->add( (string) $id, (string) $title, (string) $content, (array) $options );

// Boot things up.
$my_theme_notices->boot();

在您使用以下代码实例化Notices对象后$my_theme_notices = new \WPTRT\AdminNotices\Notices();,您可以使用add()方法添加新通知。

此方法的参数是

$options参数是一个数组,可以包含以下可选项

示例

您可以将以下代码添加到您主题的现有代码中。

首先,我们需要实例化Notices对象

use WPTRT\AdminNotices\Notices;

$my_theme_notices = new Notices();

添加一个简单、默认的通知

$my_theme_notices->add(
    'my_theme_notice',                           // Unique ID.
    esc_html__( 'Notice Title', 'textdomain' ),  // The title for this notice.
    esc_html__( 'Notice content', 'textdomain' ) // The content for this notice.
);

上述示例将创建一个新通知,该通知将在所有仪表板页面上显示。当通知被取消时,将在数据库中保存一个新的具有键wptrt_notice_dismissed_my_theme_notice的选项。键通过将$id附加到选项的默认前缀(wptrt_notice_dismissed)并使用下划线分隔来创建。

添加一个更定制化的通知

$my_theme_notices->add(
    'my_notice',                                  // Unique ID.
    esc_html__( 'Notice Title', 'textdomain' ),   // The title for this notice.
    esc_html__( 'Notice content', 'textdomain' ), // The content for this notice.
    [
        'scope'         => 'user',       // Dismiss is per-user instead of global.
        'screens'       => [ 'themes' ], // Only show notice in the "themes" screen.
        'type'          => 'warning',    // Make this a warning (orange color).
        'alt_style'     => true,         // Use alt styles.
        'option_prefix' => 'my_theme',   // Change the user-meta prefix.
    ]
);

上述示例将创建一个新通知,该通知仅会在仪表板中的“主题”屏幕上显示。当通知被取消时,将保存一个新的用户元数据,存储的用户元数据键为my_theme_my_notice。键通过将$id附加到我们定义的option_prefix并使用下划线分隔来创建。

可以使用Notices类添加多个通知。完成添加通知后,您必须运行boot方法,以便将通知添加到仪表板。

$my_theme_notices->boot();

总结以上所有内容,添加admin通知的完整示例如下

$my_theme_notices = new \WPTRT\AdminNotices\Notices();
$my_theme_notices->add( 'my_theme_notice', __( 'Title', 'textdomain' ), __( 'Content', 'textdomain' ) );
$my_theme_notices->boot();

自动加载

您需要使用自动加载器。理想情况下,这将是一个Composer。但是,我们有基本自动加载器可用于与主题一起使用(如果需要)。

Composer

从命令行

composer require wptrt/admin-notices

WPTRT自动加载器

如果使用WPTRT自动加载器,请使用以下代码

include get_theme_file_path( 'path/to/autoload/src/Loader.php' );

$loader = new \WPTRT\Autoload\Loader();
$loader->add( 'WPTRT\\AdminNotices\\Notice', get_theme_file_path( 'path/to/admin-notices/src' ) );
$loader->register();