WordPress维护模式实现指南(含插件与无插件方案)

本文详细讲解WordPress网站维护模式的两种实现方式:通过添加PHP代码到子主题functions.php文件实现无插件方案,以及使用LightStart插件配置方案。包含完整的代码示例和操作步骤,适合开发者参考使用。

WordPress维护模式(含插件与无插件方案)

WordPress维护模式在我们需要对WordPress网站进行重大更改(自定义代码和/或数据库更改)时是必需的,这样网站的前端就不会对访客开放。

无插件的WordPress维护模式

将以下代码添加到您的子主题的functions.php文件中。

如果您没有子主题,可以轻松创建一个。请参阅这篇文章。

使用此代码,网站(包括管理面板和前端)仅对管理员可用。任何其他用户将看到维护模式消息。

启用WordPress维护模式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * 维护模式
 */
function wp_maintenance_mode() {
     if ( ! current_user_can( 'administrator' ) ) {
        wp_logout();
    }
     wp_die( '<h1>网站正在进行计划维护</h1><br />请稍后再来查看。' );
}

/**
 * 检查当前页面是否为登录页面
 *
 * @return bool
 */
function is_wp_login() {
    if ( isset( $GLOBALS['pagenow'] ) && 'wp-login.php' === $GLOBALS['pagenow'] ) {
        return true;
    }
     return false;
}

if ( false === is_user_logged_in() && false === is_wp_login() ) {
    add_action( 'get_header', 'wp_maintenance_mode' );
} else {
    if ( ! current_user_can( 'administrator' ) ) {
        add_action( 'admin_init', 'wp_maintenance_mode' );
    }
}

禁用WordPress维护模式

只需注释掉add_action行(或删除整个if块):

1
2
3
4
5
6
7
if ( false === is_user_logged_in() && false === is_wp_login() ) {
    //add_action( 'get_header', 'wp_maintenance_mode' );
} else {
    if ( ! current_user_can( 'administrator' ) ) {
        //add_action( 'admin_init', 'wp_maintenance_mode' );
    }
}

使用插件的WordPress维护模式

您可以使用许多插件。

在本教程中,我们使用LightStart - Maintenance Mode, Coming Soon and Landing Page Builder

安装并激活插件。

您可能希望使用许多可用选项:

菜单 ⟶ 设置 ⟶ LightStart

但基本设置是:

LightStart

结果是:

LightStart - 维护模式

记得清除缓存(如果有),否则插件可能无法工作。

comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计