Using the WordPress API from pages outside of WordPress
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> </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.
























Is it possible to call the content from a separate website? For example, I have a blog at site01.com. I want to display a specific topic or category from that blog on a non WP related page on site02.com (essentially use one WP to update news, etc. on one (or multiple) sites.
Is this feasable?
Comment by PACKER — April 15, 2010 @ 2:48 pm
[...] 发现有如下之参考: see: http://www.webopius.com/content/139/using-the-wordpress-api-from-pages-outside-of-wordpress [...]
Pingback by 在外部使用Wordpress API ‹ 戈壁滩上的狗尾巴花 — July 17, 2010 @ 5:03 pm
Hi, thanks for your post.
but when i try this, i found every time refresh the page, it will do query_posts() once(SELECT first ten post)
So, i think we’d better to include wp-load.php instead of ‘wp-blog-header.php’, have a try~
for more info, visit my post: http://liguoliang.com/2010/07/1312/
Comment by guoliang — July 17, 2010 @ 5:06 pm
[...] this Facebook app will not be a WordPress plugin as of yet, we need to apply a little trick and add the following to the [...]
Pingback by Facebook Associates — June 3, 2011 @ 7:50 am