如何配置数据库为WordPress自动检测本地和实时服务器


How to configure Database for WordPress to automatically Detect Local and Live Server?

我正在做一个WordPress项目,其中有一个本地开发环境和一个远程服务器环境。

我想设置wp-config来检测它是本地的还是远程的。

如果是本地的,则定义一个数据库连接,如果是远程的,则定义另一个数据库连接。

我已经看到这是通过创建一个配置与谷歌应用引擎使用实现的。

if (isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'],'Google App Engine') !== false) {
    /** Live environment Cloud SQL login and SITE_URL info */
    define('DB_HOST', ':/cloudsql/pro-tracker-639:wordpress');
    define('DB_USER', 'root');
    define('DB_PASSWORD', '');
} else {
    /** Local environment MySQL login info */
    define('DB_HOST', '127.0.0.1');
    define('DB_USER', 'root');
    define('DB_PASSWORD', 'password');

对于一个常规的专用主机环境,我该如何做?

一种简单的方法可能是打开HTTP_HOST并相应地定义特定于每个域的参数。

switch ($_SERVER['HTTP_HOST']) {
    case 'environment.dev' :
        define('DB_NAME', 'dev_db');
        define('DB_USER', 'dev_user');
        define('DB_PASSWORD', 'dev_password');
        define('DB_HOST', 'localhost');
        define('WP_DEBUG', true );
        define('WP_CACHE', false);
        break;
    default : // assuming this is the live environment
        define('DB_NAME', 'live_db');
        define('DB_USER', 'live_user');
        define('DB_PASSWORD', 'live_password');
        define('DB_HOST', 'db.example.com');
        define('WP_DEBUG', false);
        define('WP_CACHE', true);
}

我总是创建3个配置文件:

  • wp-local-config.dist.php
  • wp-live-config.dist.php
  • wp-test-config.dist.php

在我的主wp-config文件中,我这样做:

if ( file_exists( dirname( __FILE__ ) . '/wp-local-config.php' ) ) {
    // Local
    include( dirname( __FILE__ ) . '/wp-local-config.php' );
} elseif ( file_exists( dirname( __FILE__ ) . '/wp-test-config.php' ) ) {
    // Test
    include( dirname( __FILE__ ) . '/wp-test-config.php' );
} else {
    // Live
    include( dirname( __FILE__ ) . '/wp-live-config.php' );
}

在这些文件中,我定义了适合环境的内容:

// ===================================================
// DB config
// ===================================================
define( 'DB_NAME', '' );
define( 'DB_USER', '' );
define( 'DB_PASSWORD', '' );
define( 'DB_HOST', 'localhost' );

// ===================================================
// Various
// ===================================================
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', true );
define( 'SCRIPT_DEBUG', true );
define( 'SAVEQUERIES', true );
define( 'FS_METHOD', 'direct' );

// ===================================================
// Cache
// ===================================================
define( 'WP_CACHE', false );

在wp-live-config.php中的WP_DEBUG应该总是设置为false

每个服务器上的

从正确的文件中删除.dist