Note that simply bootstrapping directly for a one off temporary file is never the optimal solution, and bad practice, and tends to introduce lots of problems. E.g. in your case, you might have WordPress functions available, but no theme files or APIs are triggered.
Instead, there are better ways to do it. This isn’t considered bad practice without reason.
In a Browser
If you want to mess around with templates, and don’t want to create page templates, you can put this in your functions.php
:
add_filter( 'template_include', function($template) {
return isset($_GET['test']) ? locate_template(['test.php']) : $template ;
}, 99 );
Now, when you visit yoursite.com/?test
, it will load the test.php
template in your theme.
You could even expand this further:
add_filter( 'template_include', function($template) {
return !empty($_GET['test']) ? locate_template(['test/'.$_GET['test'].'.php') : $template ;
}, 99 );
Now you can place any PHP file inside a test
sub folder in your theme, and access it via yoursite.com/?test=foo
to load test/foo.php
. As a bonus, you no longer need to count how many folders up wp-load.php
is, and it will work on any WP install no matter how the folders are configured
Just don’t do this on a live server.
In CLI
Additionally, if you have WP CLI installed, you can run wp eval test.php
to do this from the command line.
You can also run wp shell
to get an interactive PHP shell with WP functions loaded, and to test cron jobs, you can run wp cron test
.
In a Cron Job, or Another Template
You can run get_template_part('test')
to load the test.php
template from somewhere else in WP.
You can also use wp cron event run --due-now
to trigger WP Cron via an actual cron job. There’s no need to bootstrap WordPress from a PHP file to get reliable cron in WordPress.
In Automated Testing
In general, you would not test templates this way. A proper test would either create posts, or mock posts. This is usually done by spawning a test environment, and pre-filling it with a database of known content, and running tests, reverting the database to the known good example in the process.
Doing this allows for integration tests using tools such as Behat which run automated browser tests by spawning headless browsers such as phantom, or even firefox instances.
Alternatively, for testing classes, you could use standard PHPUnit, combined with mocks for the WP APIs used.
Keep in mind that most major production themes on enterprise sites have some sort of tests
subfolder that gets ran by phpunit
or some other CI tool