WordPress Tips: How to query post title and excerpt using PHP

I was working on a client’s website, which was running on WordPress and he was using ShopperPress on that site.
And he also have one separate website for his main website.

Now he wanted me to pull some data on the other site (with the ShopperPress) and put it on the home page of his main website.

Now what I did is pretty simple, I just wanted to share this..

Here’s what I did:

<?php
if (!$link = mysql_connect('localhost', 'DBUSER', 'DBPASS')) {
echo 'Could not connect to mysql';
exit;
} if (!mysql_select_db('DATABASE NAME HERE', $link)) {
echo 'Could not select database';
exit;
}
$delrev = "DELETE FROM wp_posts WHERE post_type = 'revision'";
$sql = "SELECT * FROM `wp_posts` ORDER BY `wp_posts`.`post_type` DESC LIMIT 0, 3 ";
$w = mysql_query($delrev);
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}

if (!$w) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}

if ($row['post_type'] = "post" ) {

while ($row = mysql_fetch_assoc($result)) {
echo "<a href=\"";
echo $row['guid'];
echo "\">";
echo substr($row['post_title'], 0, 46);
echo "</a>";

echo substr($row['post_excerpt'], 0, 160);

}

}
mysql_free_result($result);
mysql_close();
?>

Just Replace the DBUSER with your Database Username, DBPASS with your Database Password and of course for the DATABASE NAME for your database name. (Obviously)

Now I added this code to avoid duplication of the post that we are going to query.

$delrev = "DELETE FROM wp_posts WHERE post_type = 'revision'";

That will actually tell the database to delete all autosave files that are on our database because we want to avoid duplication.

$sql = "SELECT * FROM `wp_posts` ORDER BY `wp_posts`.`post_type` DESC LIMIT 0, 3 ";

And also DESC LIMIT 0, 3 … Just means that we are limiting it only to 3 data.
You can actually just figure out everything for yourself.