Display Posts Outside WordPress

Display Posts Outside WordPress

From ThaiiS Note (Wiki)

Jump to: navigation, search

Display Posts Outside WordPress

Contents

01

If setup WordPress in a subdirectory on your site (such as /blog) and wish to display the latest blog(s) on your front page, for instance, you can. Add this code to the top of the page you are including the posts on:

<?php
// Include Wordpress
define('WP_USE_THEMES', false);
//define('WP_USE_THEMES', true);
require('./blog/wp-blog-header.php');
query_posts('showposts=1');
?>

Note: This will show the latest post. If you wish to show more, say the last 5 posts, change showposts=1 to showposts=5 (or whatever number you wish).

02

Then add the following where you desire the blog posts to appear:

<?php while (have_posts()): the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
<p><a href="<?php the_permalink(); ?>">Read more...</a></p>
<?php endwhile; ?>

03

The above will pull the post title, show the excerpt and provide a link to read more. If you would rather just have the post title show as a link, using the following:

<?php while (have_posts()): the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php endwhile; ?>

If you wish to show a specific post, change the query_post line. Other items of interest

04

To show a specific page, you can change the query_posts line to reference either the page number or page name. Both methods are shown:

query_posts('page_id=7'); // page number
query_posts('pagename=about'); // page name

WordPress provides a listing of template tags usable after calling in wp-blog-header.php

Credit: Post inspired by information found at Corvid Works.

Bonus

You can even use this code to display blog posts on a completely separate web site, as long as it’s on the same server and you have filesystem access to the Wordpress directory on the original site. Simply modify the require() in the first block on this page to use the full path to your Wordpress installation:

<?php
// Include Wordpress 
define('WP_USE_THEMES', false);
require('/var/www/example.com/blog/wp-load.php');
query_posts('showposts=1');
?>

Note: PHP restrictions such as open_basedir may prevent this last example from working.

other note

Try to add

global $wpdb;
require_once('wp-blog-header.php');