December 2, 2008

Using the WordPress API from pages outside of WordPress

Filed under: Tips — Tags: , , — Webopius @ 9:35 pm

I know, it’s not the a very catchy title but how else can you describe it?! If you have a wordpress blog installed in, say the blog directory, how can you retrieve posts and other WordPress data from pages outside of the WordPress directory structure?

Being able to do this allows you to use the power of WordPress from anywhere within your site. WordPress can be your Content Management System (CMS), Security System, Category Manager, you name it.

The Solution

From your standalone page (any .php page independent from WordPress), you can get hold of the Posts (or use any other WordPress API features such as security etc) by using the WordPress API like this:

Step 1

At the very top of your page before anything else, include these lines:


<?php define('WP_USE_THEMES', false); ?>
<?php require('wp-blog-header.php');?>

(You may need to specify the path to the wp-blog-header.php if your standalone page is outside of the WordPress directory structure – note this is a relative file path not a URL)

Step 2

Now, to retrieve, say the most recent 7 Posts that are all in Category 2, include this block of code:


<?php query_posts('cat=2&showposts=7'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
<?php endwhile; else: ?>
<p>&nbsp;</p>
<?php endif; ?>

Here’s another example. If you want to get the details of the current WordPress user:


global $userdata;
get_currentuserinfo();
$userid = $userdata->ID;

You can now use all the power of WordPress from any page on your site.

  • Tags