Wordpress Loop on Non-Wordpress Pages
I was looking for an easy code snippet to put the latest blog posts on the EyeStorm index page using the Wordpress loop. I remember it took me quite a bit of searching, that I had to keep trying different keyword combinations until I finally found something to help me. Today, I wanted to change the sort order of the posts and no matter if I changed it from ASC to DESC, nothing happened. I realized the code I had pilfered had some syntax errors. Having some PHP/MySQL knowledge, I fixed them and spent another ten minutes looking for that post again so I could add a comment with the syntax fix to no avail. So, I decided I would post this in case other people are looking for the same thing and having problems finding it.
Now that I’ve bored you with the short story, here’s the code.
<?php
$how_many=3; //How many posts do you want to show
require_once("blog/wp-config.php"); // Change this for your path to wp-config.php file ?>
<ol id="whats-new">
<?php
// if post state is published and the post type is a post (and not a page), display it. You can remove the AND 'post_type' = \"post\" line to grab both posts and pages. Sort ASC or DESC (Descending).
$news=$wpdb->get_results("SELECT `ID`,`post_title` FROM $wpdb->posts
WHERE `post_status`= \"publish\" AND `post_type` = \"post\" ORDER BY POST_DATE DESC LIMIT ".$how_many);
foreach($news as $np){
printf ("<li style='padding-bottom:7px;'><a href=\"blog/index.php?p=%s\">%s</a></li>", $np->ID,$np->post_title);
}?>
</ol>
October 26th, 2008 at 9:58 am
Revised the code today to add some more select options, fixed a bug in the code.
December 8th, 2008 at 11:35 am
Hi David,
I am currently trying to design a site with WP as a content management system. The landing page is currently HTML/CSS; I would like it when a page is created a link is added to the home page. I am using [] to create a menu for the pages, on the fly.
Can I adapt your script to display the pages on my home-page, rather manually creating the links?
Any help would be greatly appreciated.
Regards,
Steven.
February 1st, 2009 at 2:58 pm
The “Just Blogged” links on the EyeStorm homepage are using the same PHP code as listed here. With every new blog post (granted there haven’t been many, too busy) those linsk are dynamically updated. No need to add manual links every again
January 20th, 2010 at 11:13 am
Is it possible to remove the href and fetch only the post content? It would be helpful to post content from membership pages to tempt the visitors to sign up for membership
January 20th, 2010 at 11:15 am
Here’s the code that fetches the content
get_results(”SELECT `ID`,`post_title`,`post_content` FROM $wpdb->posts
WHERE `post_status`= \”publish\” AND `post_type` = \”post\” ORDER BY POST_DATE DESC LIMIT “.$how_many);
foreach($news as $np){
printf (”%s“, $np->ID,$np->post_content);
}?>