Displaying WordPress titles on home page (not a WordPress page)

andylpsx

New Member
Messages
29
Reaction score
1
Points
3
I built a website using basic html, JavaScript and Jquery and wanted to add my recent blog posts to the home page without having to manually editing the source code. I am working with a test php page that I have gotten to work with displaying the titles but I don't want to display EVERY title just the last 5 or so. The way it displays is from oldest to newest as well. I just want the 5 newest. How do I do this? I am far from an expert with PDO, php and SQL. This is what I have so far.
PHP:
<?php
$db = new PDO('mysql:host=localhost;dbname=test_wp166;charset=utf8', 'test_wp7474', '*****');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
foreach($db->query('SELECT post_title, post_status FROM wp_posts') as $post_title) {
if ($post_title['post_status'] === "publish") {
    echo $post_title['post_title'].'<br />'  ;
    }
}
?>

WordPress also adds to the database every time a post is edited causing multiple post_title's to be the same. That is why I added an if to only display what has been been classified as 'publish' by the post_status
Any help would be appreciated.
 

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
Off the top of my head ...
Add the restriction
WHERE post_status= 'publish'​
in your MySQL query -- that way you don't have to filter them in your script
Use:
ORDER BY whateverFieldIsTheFieldForTime DESC​
to put the newest entries first
Use:
LIMIT 5​
to only get 5 results
 

andylpsx

New Member
Messages
29
Reaction score
1
Points
3
Thank you so much! It worked the new code I have is:
Code:
<?php
$db = new PDO('mysql:host=localhost;dbname=test_wp166;charset=utf8', 'test_wp7474', '*****');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
foreach($db->query('SELECT post_title, post_status, post_date FROM wp_posts WHERE post_status = "publish" ORDER BY post_date DESC LIMIT 5') as $post_title) {
    echo $post_title['post_title'].'<br />'  ;
}
?>

I've been trying to get this to work for 3 months now. Thanks for helping.
 
Top