我需要创建一条新路线all
它只返回所有帖子的指定字段。
add_action( \'rest_api_init\', function () {
register_rest_route( \'custom\', \'all\' ,array(
\'methods\' => \'GET\',
\'callback\' => \'get_all\'
) );
} );
我需要为所有职位,他们的id,标题,链接。
我无法创建get_all
作用
function get_all ( $params ){
$posts = get_posts(
array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\'
)
);
// parse all posts and for each post returns only the specified fields
wp_reset_postdata();
return rest_ensure_response( $data );
}
最合适的回答,由SO网友:cmii 整理而成
建立此函数用于返回每个帖子的指定字段。
function get_all ( $params ){
$posts = get_posts( array(
\'offset\' => 0,
\'post_status\' => \'publish\'
) );
if ( empty( $posts ) ) {
return null;
}
$posts_data = array();
foreach( $posts as $post ) {
$posts_data[] = (object) array(
\'id\' => $post->ID,
\'date\' => $post->post_date,
\'date_gmt\' => $post->post_date_gmt,
\'modified\' => $post->post_modified,
\'title\' => $post->post_title,
\'content\' => $post->post_content,
\'category\' => get_the_category_by_ID($post->post_category[0]),
\'link\' => get_permalink($post),
);
}
return $posts_data;
}