You may ask “Why did you want to do this?!?”… It is quite simple: while trying to improve my personal homepage (still work in progress…) I wanted to be able to display my last WordPress Articles on it.
Before starting to generate wild SQL queries to get the needed data from my database, I did some research and found out that you can get your last WordPress posts by adding the following PHP code to your page (as long as you are on the same server and have access to the WordPress directory):
define('WP_USE_THEMES', false); require('path/to/your_wp_directory/wp-load.php'); query_posts('showposts=5');
Here is what this code does:
- The first line tells WordPress that no template has to be displayed
- The second line gets the
wp-load.phpfile, which loads the WordPress application and API; this file makes the WordPress content, and also its functions, available in the file where you put the above code
- The third, and last, line performs a query that gets the specified number of posts (in this case the last five)
Displaying the data
To actually display the posts fetched by the above code, you will have to use a WordPress loop as follows:
while (have_posts()): the_post(); // Display post data here... endwhile;
This loop will contain the number of posts specified in
Inside the loop you can get all the post data available inside WordPress, like the post date, title, body, excerpt, permalink, and so on. All you have to do is embed this data inside your desired HTML where you want to output your posts and you are done.
Complete loop example
Here is an example of a complete loop to output the date, title, permalink and excerpt of the posts:
while (have_posts()): the_post(); echo '<p class="date">' . the_date() . '</p>'; echo '<h2 class="title"><a href="' . the_permalink() . '">' . the_title() . '</a></h2>'; echo the_excerpt(); endwhile;
If you need to get other post data in your loop, you can have a look at the WordPress documentation about The Loop.
This technique is very useful if you need to output post data in a simple way outside your WordPress website. The only thing you need is an access to your WordPress directory in order to load the needed file
As usual, feel free to share your thoughts and implementations with me.