Accessing WordPress data from outside WordPress

(img by shindohd)

There are times when you want to access the data from your WordPress database from a webpage outside of your WordPress installation. This can be done by using the mysql_connect of PHP and selecting the data with some genuine SQL statements. This will work but it has the substantive disadvantage that the WordPress database is changed now and then and that the SQL statement will fail sooner or later.

There has to be a better solution and there is one! Simply use the function provided by WordPress itself to access the data. It’s as simple as this code:

include '../blog/wp-blog-header.php';

In this example WordPress is installed in the directory “../blog” relative to the directory of the current script. You have to adapt it to your installation, of course. Now you can access the database using the $wpdb-instance, i.e.

$post_id = 666;
$sql = "select post_title from $wpdb->posts where ID=$post_id";
$title = $wpdb->get_var($sql);

Ok, if Automattic decides to change the row names you’ve lost again. So you should completely avoid direct database calls and use the functions build into WordPress which are also available after including the above file:

$post_id = 666;
$title =  get_the_title($post_id);

This should be a safe call for a very long time!


Comments

One response to “Accessing WordPress data from outside WordPress”

Leave a Reply

Your email address will not be published. Required fields are marked *