Access WordPress From An External Script

The reasons accessing WordPress from an external script are endless. I often use this solution to test my plugins in a sandbox environment, do some stuff by a linked cron job or as the title already says for external applications. This solution is the XMLRPC, in any case, preferable. Assuming that the WordPress installation is located on the same server as the application!

If you are familiar with the internal WordPress function, the advantage with this method is terrific.

And here’s the code which makes it possible

<?php

ob_start();
// suppress the theme output to receive a blank page
define('WP_USE_THEMES', false);
// load and initial the wordpress framework
require_once(dirname(__FILE__).'/wp-load.php');
ob_end_clean();
....

That’s it!

With this code snippet, you have full access to your WordPress installation and are in the position to do what you want to do. Even to create a new post or get posts that belong to a taxonomy. As I wrote at the beginning already, the possibilities are endless.

If you have an external script which is accessible from outside (public website folder), it’s better to secure it. The easiest way to do this is to ensure that you logged in and possibly are assigned to the administrator group.

<?php

// suppress the theme output to receive a blank page
define('WP_USE_THEMES', false);
// load and initial the wordpress framework
require_once(dirname(__FILE__).'/wp-load.php');
ob_end_clean();

// if an administrator is logged in, continue executing the script
if(!is_user_logged_in() or !current_user_can('administrator'))
{
     // otherwise redirect the request to the login page
     wp_redirect(wp_login_url(), 301);
     exit;
}
...
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn