if(isset($_GET[\'api\']) ) {
if ($_GET[\'api\'] == \'json\'){
$args = array(
\'post_type\' => \'post\'
);
$query = new WP_Query( $args ); // $query is the WP_Query Object
$posts = $query->get_posts(); // $posts contains the post objects
foreach( $posts as $post ) { // Pluck the id and title attributes
$output[] = array(
\'id\' => $post->ID,
\'title\' => $post->post_title,
\'content\' => $post ->post_content,
\'imageurl\' => wp_get_attachment_url( get_post_thumbnail_id($post->ID) )
);
}
header("content-type: application/json");
echo json_encode( $output );
}
exit();
}
}
这就是我得到的结果:
[
{
"id": 95,
"title": "See you next year!",
"content": "Lorem ipsum",
"imageurl": "http://localhost/....(random url)dsad.jpg"
},
{
"id": 19,
"title": "Early bird tickets",
"content": "that is good",
"imageurl": http://localhost/....(random url)dsada.jpg"
}
]
如何修改它,使我只能访问ID或标题,而不是全部?
最合适的回答,由SO网友:David Lee 整理而成
尝试以下操作:
if (isset($_GET[\'api\'])) {
if ($_GET[\'api\'] == \'json\' && isset($_GET[\'id\'])) {
$args = array(
\'p\' => $_GET[\'id\'],
\'post_type\' => \'any\'// ID of a page, post, or custom type
);
$query = new WP_Query($args); // $query is the WP_Query Object
$post = $query->post; // $post contains the post object
header("content-type: application/json");
echo json_encode($post);
}
exit();
}
get post 将检索单个帖子,它将返回一个数组,以便直接转到json\\u encode,您必须将其添加到URL“id=XX”,其中X是一个数字。
如果您有最新版本的wordpress,我建议您使用内置apiWP REST Api