Using WordPress with Composer and .env file

Work with WordPress is to use Composer for packages, and to add a .env file to your project that contains many of the sensitive code and variables that should be kept separate from your WordPress code /repository.

Step 1

Install WordPress in the application’s public_html folder (see here)

Step 2

Open a terminal and navicate to the application’s root directory. In Visual Studio Code: Terminal > New Terminal

If you have composer already installed on your system/platform (if not see articles like this), and allow the answers to default.

> composer init

Package name (<vendor>/<name>): vendor/name
Description []: // leave empty
Author: Roland Loesslein <info@weaintplastic.com>
Minimum Stability []: // leave empty if not specified
License []: // leave empty if not specified
Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no
Do you confirm generation [yes]? yes

Step 3

Then, Install a package to setup and handle .env files

composer require vlucas/phpdotenv

Step 4

Create a file in your root directory called .env

Add items like the following to the .env file:

DB_NAME= “mydatabase”
DB_USER= “myusername”
DB_PASSWORD=  “mypassword”

Step 5

Add the following to the wp-config.php file:

require_once(__DIR__ . '[SLASH]..[SLASH]vendor[SLASH]autoload.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__.'[SLASH]..[SLASH]');
$dotenv->load();

And include variables to wp-config.php or other wordpress/PHP files with:

define('DB_NAME', $_ENV['DB_NAME']);
define('DB_USER', $_ENV['DB_USER']);
define('DB_PASSWORD', $_ENV['DB_PASSWORD']);

This then allows you to separate variables and passwords from your code

0 0 votes
Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

0
Would love your thoughts, please comment.x
()
x