WordPress 最新文章 JSON输出(API)

以JSON方式输出最新文章的代码

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 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);

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this post. TrackBack URL