Find WordPress root directory in bash without WP-CLI

Simple bash script to find your WordPress root

Ever need to run a script outside of WordPress and need to know the WordPress root directory?

while [ ! -e wp-config.php ]; do
  if [ $pwd/ = / ]; then
    echo "No WordPress root found" >&2; exit 1
  fi
  cd ../
done
if [ -e wp-config.php ]; then
  wproot=$(pwd)
fi

Use cases:

  • Custom shell scripts to sync local and remote folders and databases.
  • Docker workflows where wp-cli wp commands won’t work.
  • Webpack/Grunt workflows where you might be issuing commands from the theme folder instead of the WordPress root.

How to use

  • put this code at the top of any script like myscript.sh.
  • set permissions with chmod u+x myscript.sh.
  • Use ${wproot} as a variable in any path.
    • Example echo "Uploads path is ${wproot}/wp-content/uploads".

Caveats

This is a simple script and may not work under all conditions. It will not work if:

  • your wp-config.php file is not stored in your WordPress root
  • your wp-config.php file is rename

Admittedly the conditions under which you might need this are pretty rare. I needed it for a visual regression test script that needs to traverse several folders and issue various commands, all without wp-cli or WordPress functions.

Suggestions for improvement are welcome.