Skip to content

WordPress recent posts as JSON

For an update to one of my web projects I went looking for a way to get the recent posts as JSON instead of using the RSS feed. I personally find JSON much easier to deal with than RSS, so that’s the route I wanted to take.

This does us a couple of other functions from my bag of tricks. The days_ago and shorten_string functions are used to make everything a bit friendlier.

// include our wordpress functions
// change relative path to find your WP dir
define('WP_USE_THEMES', false);
require('./wp-config.php');
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();

$posts = get_posts(array(
        'numberposts' => 5,
        'offset' => 0,
        'orderby' => 'post_date',
        'order' => 'DESC',
        'post_type' => 'post',
        'post_status' => 'publish'
        ));
$json = array();
$json['err'] = false;

if ($posts) {
    foreach ($posts as $post) {
        $ray = array();
        the_post();
        $ray['id'] = $post->ID;
        $ray['date'] = $post->post_date;
        $ray['timestamp'] = strtotime($post->post_date);

        $ago = days_ago($ray['date'], date('n/j/Y g:i a'));
        $ray['ago'] = ($ago == "") ? false : $ago;
        $ray['contents'] = shorten_string(strip_tags($post->post_content), 40);
        $ray['link'] = $post->guid;
        $ray['title'] = $post->post_title;
        $ray['link'] = '<a href="'.$post->guid.'">'.$post->post_title.'</a>';

        // New if <= 5 days ago
        $ray['isNew'] = date('U') - $ray['timestamp'] <= 60 * 60 * 24 * 5;

        $json['posts'][] = $ray;

    }
}

header('Content-type: application/json;');
echo json_encode($json);

A few lines to pay attention to:

4 – This is the path to the wp-blog-header.php file relative to where you put this code. As it’s written above this would go in the same folder as wp-blog-header. Had to update this one below because WordPress was returning a 404.

4-8 – This is the path to the wp-config.php file relative to where you put your script. As written, the script would be in the same folder as wp-config.php. Thanks to this post on Androgen.com for the fix to not have WordPress display a 404 error even though the page exists.

10-19 – Tells WP how many posts to get, and how to query them. What’s there will pull the 5 most recent posts out of any category, sorted by post date in descending order, and only posts that are published.

31 – Strips out any HTML tags from $post->post_content and uses shorten_string to limit it to 40 words. This is what I needed for my project, but it should be easy enough to change it for your needs.

37 – Flags the post as new if it was published within the past 5 days. Again, something I needed for my project that you may not need.

Published inProgramming

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *