2

How can I find the WordPress root directory in Bash without using WP-CLI?

3
  • 1
    Can you provide some context as to why WP CLI is specifically excluded in the question? Also, the WP root directory doesn't make sense as a term once you start doing subdirectory installs such as those composer would install
    – Tom J Nowell
    Jan 26, 2019 at 0:21
  • Sure Tom. My current install uses Docker. There's no MySQL server running in my MacOS and wp does nothing without MySQL running. I could ssh into the docker container and use wp there, but that would only give me paths inside the docker container; for BackstopJS to work in my instance I needed various paths on the host machine and not the Docker paths. Ditto for rsync'ing plugins between local and remote devs (though there are other ways to sync plugins, I know).
    – Slam
    Jan 27, 2019 at 4:45
  • This might also be useful in installs where the hosting provider does not provide or allow wp-cli.
    – Slam
    Jan 27, 2019 at 4:52

1 Answer 1

2

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.

2
  • 1
    Note that the wp-config.php file can be one level up, in which case this will generate the wrong result
    – Tom J Nowell
    Jan 26, 2019 at 0:21
  • Yup, I added to that the Caveats section at the bottom. Is there any other file or folder that is guaranteed to be at wp root? I could search for that instead.
    – Slam
    Jan 27, 2019 at 4:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.