One of my students wants to search WordPress.com entries in her project. Here’s how!
<?php
// Change this!
$query = "There's no such name as Brahbrah";
// WordPress supplies search results in JSON format.
$url = "http://en.search.wordpress.com/?f=json&q=".urlencode($query);
$contents = file_get_contents($url);
$posts = json_decode($contents);
// Now loop through all of the results
if($posts != NULL)
foreach($posts as $post):
?>
<!-- Here is where all of the entries get printed out -->
<h2><a href="<?php echo $post->link; ?>"><?php echo $post->title; ?></a></h2>
<p>by <?php echo $post->author; ?> on
<?php echo date('l jS of F Y h:i:s A', $post->epoch_time); ?></p>
<p><?php echo $post->content; ?></p>
<?php endforeach; ?>
PS: If your server complains about ‘file_get_contents’, paste in this function and replace ‘file_get_contents’ with ‘curl_get_contents’
Searching WordPress.com with PHP
One of my students wants to search WordPress.com entries in her project. Here’s how!
<?php // Change this! $query = "There's no such name as Brahbrah"; // WordPress supplies search results in JSON format. $url = "http://en.search.wordpress.com/?f=json&q=".urlencode($query); $contents = file_get_contents($url); $posts = json_decode($contents); // Now loop through all of the results if($posts != NULL) foreach($posts as $post): ?> <!-- Here is where all of the entries get printed out --> <h2><a href="<?php echo $post->link; ?>"><?php echo $post->title; ?></a></h2> <p>by <?php echo $post->author; ?> on <?php echo date('l jS of F Y h:i:s A', $post->epoch_time); ?></p> <p><?php echo $post->content; ?></p> <?php endforeach; ?>PS: If your server complains about ‘file_get_contents’, paste in this function and replace ‘file_get_contents’ with ‘curl_get_contents’
function curl_get_contents($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)'); curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com'); curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($ch, CURLOPT_AUTOREFERER, true); $data = curl_exec($ch); curl_close($ch); return $data; }