Get WordPress post outside of WP

26.Aug.2010

Sometimes there is a need to get posts outside of WordPress. In order to get latest couple of posts and present them as news outside of WP, I have written a function that might be useful.

This function has two parameters. First one is database connection, and second is optional array of parameters used to narrow down list of posts. How to use this function, see snippet below this one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function getPostList($db, $params = array()) {
 	$sql = 'SELECT post_title, post_content, post_date, guid, post_name
			FROM wp_posts
			WHERE post_status="publish"';
 
	if(!empty($params['where']))
		foreach($params['where'] as $where)
			$sql .= ' AND ' . $where . ' ';
 
	if(empty($params['order'])) $sql .= ' ORDER BY post_date DESC ';
	if(!empty($params['limit'])) $sql .= ' LIMIT 0,' . $params['limit'];
 
 	$result = mysql_query($sql, $db);
 
	$return = array();
 	while($row = mysql_fetch_array($result))
		$return[] = $row;
 
	return $return;
}

This snippet shows how to use function above in order to get and output list of WP posts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//connect to blog
$dbhostname = 'localhost';
$dbname = 'your_db_name';
$dbusername = 'your_username';
$dbpassword = 'your_password';
$connect = mysql_connect($dbhostname, $dbusername, $dbpassword);
mysql_select_db($dbname);
mysql_query("SET NAMES utf8");
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET COLLATION_CONNECTION='utf8_general_ci'");
$dbBlog = $connect;
 
//get list of posts
$listPosts = getPostList($dbBlog, array('limit' => 4));
$tagPattern = '~<[^>]*>~';
 
//output list of WP posts
foreach($listPosts as $post) {
	$postContent = $post['post_content'];
	//remove tags
	$postContent = preg_replace($tagPattern, '', $postContent);
 
	echo '
		<h1>' . $post['post_title'] . '</h1>
		<p>
			' . substr($postContent, 0, 600) . '...<br/>
		</p>
	';
}