Wordpress 如何使用 WP_REST_Posts_Controller 获取特定的 post 数据
Wordpress how to get specific post data using WP_REST_Posts_Controller
如何在 foreach 循环中获取特定的 post 数据? (仅标题为例)
这是我的 PHP(returns 所有 post 数据):
function myspace_get_posts_by_tag(WP_REST_Request $request) {
$slug = $request['slug'];
$page = $request['page'];
$term = get_term_by('slug', $slug, 'post_tag');
$posts_per_page = 1;
$args = array(
'tag__in' => $term->term_id,
'posts_per_page' => $posts_per_page,
'paged' => $page,
'orderby' => 'date',
'order' => 'desc',
);
$query = new WP_Query( $args );
$max_pages = $query->max_num_pages;
$total = $query->found_posts;
$posts = $query->posts;
$controller = new WP_REST_Posts_Controller('post');
foreach ( $posts as $post ) {
$response = $controller->prepare_item_for_response( $post, $request );
$data[] = $controller->prepare_response_for_collection( $response );
}
$response = new WP_REST_Response($data, 200);
$response->header( 'X-WP-Total', $total );
$response->header( 'X-WP-TotalPages', $max_pages );
return $response;
}
为了示例,我删减了一些代码。
您正在使用 WP_Query()
稍后在 foreach 循环中获取 post。
在这种情况下,$post 是 WP_Post Object。所以你可以访问它的属性,在你的例子中 - post 的标题:
$post->post_title
如何在 foreach 循环中获取特定的 post 数据? (仅标题为例)
这是我的 PHP(returns 所有 post 数据):
function myspace_get_posts_by_tag(WP_REST_Request $request) {
$slug = $request['slug'];
$page = $request['page'];
$term = get_term_by('slug', $slug, 'post_tag');
$posts_per_page = 1;
$args = array(
'tag__in' => $term->term_id,
'posts_per_page' => $posts_per_page,
'paged' => $page,
'orderby' => 'date',
'order' => 'desc',
);
$query = new WP_Query( $args );
$max_pages = $query->max_num_pages;
$total = $query->found_posts;
$posts = $query->posts;
$controller = new WP_REST_Posts_Controller('post');
foreach ( $posts as $post ) {
$response = $controller->prepare_item_for_response( $post, $request );
$data[] = $controller->prepare_response_for_collection( $response );
}
$response = new WP_REST_Response($data, 200);
$response->header( 'X-WP-Total', $total );
$response->header( 'X-WP-TotalPages', $max_pages );
return $response;
}
为了示例,我删减了一些代码。
您正在使用 WP_Query()
稍后在 foreach 循环中获取 post。
在这种情况下,$post 是 WP_Post Object。所以你可以访问它的属性,在你的例子中 - post 的标题:
$post->post_title