Skip to content

Instantly share code, notes, and snippets.

@jdmwood
Last active September 28, 2023 14:37
Show Gist options
  • Save jdmwood/67205ac64b21ab4632169f9048cb0ba0 to your computer and use it in GitHub Desktop.
Save jdmwood/67205ac64b21ab4632169f9048cb0ba0 to your computer and use it in GitHub Desktop.
Script to help setting up Wordpress managed by wp-env for use with ngrok
#! /usr/bin/env python3
"""
Setup ngrok for local development with WordPress when used with wp-env. Follows instructions from
https://ngrok.com/docs/using-ngrok-with/wordpress/
Notes
-----
This essentially follows the instructions above to add in the required config into `wp-config.php`, first using
`wp-env install-path` to find the files.
I did try using `WORDPRESS_CONFIG_EXTRA` but that doesn't seem to play nicely with wp-env so I decided to just
write a Python script instead.
Note that any ngrok will also need the `--host-header=rewrite` as describe in the docs above.
"""
import os
import subprocess
import sys
from pathlib import Path
# Change to project dir
os.chdir(os.path.dirname(os.path.abspath(__file__)))
SNIPPET = """
// Added by setup-ngrok.py
// {{{
define('.COOKIE_DOMAIN.', 'REPLACEME');
define('.SITECOOKIEPATH.', '.');
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$list = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
$_SERVER['REMOTE_ADDR'] = $list[0];
}
define( 'WP_HOME', 'https://REPLACEME' );
define( 'WP_SITEURL', 'https://REPLACEME' );
$_SERVER['HTTP_HOST'] = 'REPLACEME';
$_SERVER['REMOTE_ADDR'] = 'https://REPLACEME';
$_SERVER[ 'SERVER_ADDR' ] = 'REPLACEME';
// }}}
"""
# Find the wp-config file
wp_dir = subprocess.check_output(['wp-env', 'install-path'], stderr=subprocess.DEVNULL).decode('utf-8').strip()
config_file = f"{wp_dir}/WordPress/wp-config.php"
contents_original = Path(config_file).read_text()
if '// Added by setup-ngrok.py' in contents_original:
print('wp-config.php already has the ngrok snippet. Exiting.')
exit(1)
if len(sys.argv) == 1:
ngrok_domain = input('Enter your ngrok domain (e.g. `my-custom-domain.ngrok.io`): ')
else:
ngrok_domain = sys.argv[1]
snippet = SNIPPET.replace('REPLACEME', ngrok_domain)
# Remove the existing WP_SITE_URL
contents = contents_original.replace("define( 'WP_SITEURL', 'http://localhost:8888' );", "")
# Replace the existing WP_HOME with the full snippet (this also helps us insert the snippet in the right place
# in the file - note that adding at the end doesn't work for some reason)
contents = contents.replace("define( 'WP_HOME', 'http://localhost:8888' );", snippet)
Path(config_file + '.bak').write_text(contents_original)
Path(config_file).write_text(contents)
print(f'Success!')
print(f'Config updated at {config_file}')
print(f'Backup written to {config_file + ".bak"}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment